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/bookmarks/bookmark_model.h"
36 #include "chrome/browser/bookmarks/bookmark_utils.h"
37 #include "chrome/browser/browser_process.h"
38 #include "chrome/browser/browser_shutdown.h"
39 #include "chrome/browser/character_encoding.h"
40 #include "chrome/browser/chrome_notification_types.h"
41 #include "chrome/browser/chrome_page_zoom.h"
42 #include "chrome/browser/content_settings/host_content_settings_map.h"
43 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
44 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
45 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
46 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
47 #include "chrome/browser/defaults.h"
48 #include "chrome/browser/devtools/devtools_toggle_action.h"
49 #include "chrome/browser/devtools/devtools_window.h"
50 #include "chrome/browser/download/download_item_model.h"
51 #include "chrome/browser/download/download_service.h"
52 #include "chrome/browser/download/download_service_factory.h"
53 #include "chrome/browser/download/download_shelf.h"
54 #include "chrome/browser/extensions/browser_extension_window_controller.h"
55 #include "chrome/browser/extensions/extension_prefs.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_system.h"
58 #include "chrome/browser/extensions/tab_helper.h"
59 #include "chrome/browser/favicon/favicon_tab_helper.h"
60 #include "chrome/browser/file_select_helper.h"
61 #include "chrome/browser/first_run/first_run.h"
62 #include "chrome/browser/google/google_url_tracker.h"
63 #include "chrome/browser/infobars/infobar_service.h"
64 #include "chrome/browser/infobars/simple_alert_infobar_delegate.h"
65 #include "chrome/browser/lifetime/application_lifetime.h"
66 #include "chrome/browser/notifications/notification_ui_manager.h"
67 #include "chrome/browser/pepper_broker_infobar_delegate.h"
68 #include "chrome/browser/prefs/incognito_mode_prefs.h"
69 #include "chrome/browser/profiles/profile.h"
70 #include "chrome/browser/profiles/profile_destroyer.h"
71 #include "chrome/browser/profiles/profile_manager.h"
72 #include "chrome/browser/profiles/profile_metrics.h"
73 #include "chrome/browser/repost_form_warning_controller.h"
74 #include "chrome/browser/search/search.h"
75 #include "chrome/browser/sessions/session_service.h"
76 #include "chrome/browser/sessions/session_service_factory.h"
77 #include "chrome/browser/sessions/session_tab_helper.h"
78 #include "chrome/browser/sessions/session_types.h"
79 #include "chrome/browser/sessions/tab_restore_service.h"
80 #include "chrome/browser/sessions/tab_restore_service_factory.h"
81 #include "chrome/browser/sync/profile_sync_service.h"
82 #include "chrome/browser/sync/profile_sync_service_factory.h"
83 #include "chrome/browser/sync/sync_ui_util.h"
84 #include "chrome/browser/tab_contents/background_contents.h"
85 #include "chrome/browser/tab_contents/retargeting_details.h"
86 #include "chrome/browser/tab_contents/tab_util.h"
87 #include "chrome/browser/themes/theme_service.h"
88 #include "chrome/browser/themes/theme_service_factory.h"
89 #include "chrome/browser/translate/translate_tab_helper.h"
90 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
91 #include "chrome/browser/ui/autofill/tab_autofill_manager_delegate.h"
92 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
93 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
94 #include "chrome/browser/ui/browser_command_controller.h"
95 #include "chrome/browser/ui/browser_commands.h"
96 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.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_language_state_observer.h"
102 #include "chrome/browser/ui/browser_list.h"
103 #include "chrome/browser/ui/browser_navigator.h"
104 #include "chrome/browser/ui/browser_tab_contents.h"
105 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
106 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
107 #include "chrome/browser/ui/browser_tabstrip.h"
108 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
109 #include "chrome/browser/ui/browser_ui_prefs.h"
110 #include "chrome/browser/ui/browser_window.h"
111 #include "chrome/browser/ui/chrome_pages.h"
112 #include "chrome/browser/ui/chrome_select_file_policy.h"
113 #include "chrome/browser/ui/fast_unload_controller.h"
114 #include "chrome/browser/ui/find_bar/find_bar.h"
115 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
116 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
117 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
118 #include "chrome/browser/ui/global_error/global_error.h"
119 #include "chrome/browser/ui/global_error/global_error_service.h"
120 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
121 #include "chrome/browser/ui/media_utils.h"
122 #include "chrome/browser/ui/omnibox/location_bar.h"
123 #include "chrome/browser/ui/search/search_delegate.h"
124 #include "chrome/browser/ui/search/search_model.h"
125 #include "chrome/browser/ui/search/search_tab_helper.h"
126 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
127 #include "chrome/browser/ui/singleton_tabs.h"
128 #include "chrome/browser/ui/status_bubble.h"
129 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
130 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
131 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
132 #include "chrome/browser/ui/tabs/dock_info.h"
133 #include "chrome/browser/ui/tabs/tab_menu_model.h"
134 #include "chrome/browser/ui/tabs/tab_strip_model.h"
135 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
136 #include "chrome/browser/ui/unload_controller.h"
137 #include "chrome/browser/ui/validation_message_bubble.h"
138 #include "chrome/browser/ui/web_applications/web_app_ui.h"
139 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
140 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
141 #include "chrome/browser/ui/window_sizer/window_sizer.h"
142 #include "chrome/browser/ui/zoom/zoom_controller.h"
143 #include "chrome/browser/upgrade_detector.h"
144 #include "chrome/browser/web_applications/web_app.h"
145 #include "chrome/common/chrome_constants.h"
146 #include "chrome/common/chrome_switches.h"
147 #include "chrome/common/custom_handlers/protocol_handler.h"
148 #include "chrome/common/net/url_fixer_upper.h"
149 #include "chrome/common/pref_names.h"
150 #include "chrome/common/profiling.h"
151 #include "chrome/common/search_types.h"
152 #include "chrome/common/url_constants.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/browser/web_contents_view.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/common/constants.h"
177 #include "extensions/common/extension.h"
178 #include "extensions/common/manifest_handlers/background_info.h"
179 #include "grit/chromium_strings.h"
180 #include "grit/generated_resources.h"
181 #include "grit/locale_settings.h"
182 #include "grit/theme_resources.h"
183 #include "net/base/net_util.h"
184 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
185 #include "net/cookies/cookie_monster.h"
186 #include "net/url_request/url_request_context.h"
187 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
188 #include "ui/base/l10n/l10n_util.h"
189 #include "ui/base/window_open_disposition.h"
190 #include "ui/gfx/point.h"
191 #include "ui/shell_dialogs/selected_file_info.h"
194 #include "base/win/metro.h"
195 #include "chrome/browser/ssl/ssl_error_info.h"
196 #include "chrome/browser/task_manager/task_manager.h"
197 #include "chrome/browser/ui/view_ids.h"
198 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
199 #include "ui/base/win/shell.h"
202 #if defined(OS_CHROMEOS)
203 #include "chrome/browser/chromeos/drive/file_system_util.h"
207 #include "ash/ash_switches.h"
210 using base::TimeDelta
;
211 using base::UserMetricsAction
;
212 using content::NativeWebKeyboardEvent
;
213 using content::NavigationController
;
214 using content::NavigationEntry
;
215 using content::OpenURLParams
;
216 using content::PluginService
;
217 using content::Referrer
;
218 using content::RenderWidgetHostView
;
219 using content::SiteInstance
;
220 using content::WebContents
;
221 using extensions::Extension
;
222 using ui::WebDialogDelegate
;
223 using web_modal::WebContentsModalDialogManager
;
224 using blink::WebWindowFeatures
;
226 ///////////////////////////////////////////////////////////////////////////////
230 // How long we wait before updating the browser chrome while loading a page.
231 const int kUIUpdateCoalescingTimeMS
= 200;
233 BrowserWindow
* CreateBrowserWindow(Browser
* browser
) {
234 return BrowserWindow::CreateBrowserWindow(browser
);
237 // Is the fast tab unload experiment enabled?
238 bool IsFastTabUnloadEnabled() {
239 return CommandLine::ForCurrentProcess()->HasSwitch(
240 switches::kEnableFastUnload
);
245 ////////////////////////////////////////////////////////////////////////////////
246 // Browser, CreateParams:
248 Browser::CreateParams::CreateParams(Profile
* profile
,
249 chrome::HostDesktopType host_desktop_type
)
252 host_desktop_type(host_desktop_type
),
253 app_type(APP_TYPE_HOST
),
254 initial_show_state(ui::SHOW_STATE_DEFAULT
),
255 is_session_restore(false),
259 Browser::CreateParams::CreateParams(Type type
,
261 chrome::HostDesktopType host_desktop_type
)
264 host_desktop_type(host_desktop_type
),
265 app_type(APP_TYPE_HOST
),
266 initial_show_state(ui::SHOW_STATE_DEFAULT
),
267 is_session_restore(false),
272 Browser::CreateParams
Browser::CreateParams::CreateForApp(
274 const std::string
& app_name
,
275 const gfx::Rect
& window_bounds
,
277 chrome::HostDesktopType host_desktop_type
) {
278 DCHECK(type
!= TYPE_TABBED
);
279 DCHECK(!app_name
.empty());
281 CreateParams
params(type
, profile
, host_desktop_type
);
282 params
.app_name
= app_name
;
283 params
.app_type
= APP_TYPE_CHILD
;
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
;
298 ////////////////////////////////////////////////////////////////////////////////
299 // Browser, InterstitialObserver:
301 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
303 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
304 : WebContentsObserver(web_contents
),
308 using content::WebContentsObserver::web_contents
;
310 virtual void DidAttachInterstitialPage() OVERRIDE
{
311 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
314 virtual void DidDetachInterstitialPage() OVERRIDE
{
315 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
321 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
324 ///////////////////////////////////////////////////////////////////////////////
325 // Browser, Constructors, Creation, Showing:
327 Browser::Browser(const CreateParams
& params
)
328 : type_(params
.type
),
329 profile_(params
.profile
),
331 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
332 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_
.get(),
334 app_name_(params
.app_name
),
335 app_type_(params
.app_type
),
336 cancel_download_confirmation_state_(NOT_PROMPTED
),
337 override_bounds_(params
.initial_bounds
),
338 initial_show_state_(params
.initial_show_state
),
339 is_session_restore_(params
.is_session_restore
),
340 host_desktop_type_(BrowserWindow::AdjustHostDesktopType(
341 params
.host_desktop_type
)),
342 content_setting_bubble_model_delegate_(
343 new BrowserContentSettingBubbleModelDelegate(this)),
344 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
345 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
346 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
347 bookmark_bar_state_(BookmarkBar::HIDDEN
),
348 command_controller_(new chrome::BrowserCommandController(
349 this, g_browser_process
->profile_manager())),
350 window_has_shown_(false),
351 chrome_updater_factory_(this),
353 language_state_observer_(new BrowserLanguageStateObserver(this)) {
354 // If this causes a crash then a window is being opened using a profile type
355 // that is disallowed by policy. The crash prevents the disabled window type
356 // from opening at all, but the path that triggered it should be fixed.
357 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_
));
358 CHECK(!profile_
->IsGuestSession() || profile_
->IsOffTheRecord())
359 << "Only off the record browser may be opened in guest mode";
361 // TODO(jeremy): Move to initializer list once flag is removed.
362 if (IsFastTabUnloadEnabled())
363 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
365 unload_controller_
.reset(new chrome::UnloadController(this));
367 if (!app_name_
.empty())
368 chrome::RegisterAppPrefs(app_name_
, profile_
);
369 tab_strip_model_
->AddObserver(this);
371 toolbar_model_
.reset(new ToolbarModelImpl(toolbar_model_delegate_
.get()));
372 search_model_
.reset(new SearchModel());
373 search_delegate_
.reset(new SearchDelegate(search_model_
.get()));
375 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED
,
376 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
377 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED
,
378 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
379 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED
,
380 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
381 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
382 content::NotificationService::AllSources());
383 #if defined(ENABLE_THEMES)
385 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
386 content::Source
<ThemeService
>(
387 ThemeServiceFactory::GetForProfile(profile_
)));
389 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
390 content::NotificationService::AllSources());
392 profile_pref_registrar_
.Init(profile_
->GetPrefs());
393 profile_pref_registrar_
.Add(
394 prefs::kDevToolsDisabled
,
395 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
396 profile_pref_registrar_
.Add(
397 prefs::kShowBookmarkBar
,
398 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
399 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
401 BrowserList::AddBrowser(this);
403 // NOTE: These prefs all need to be explicitly destroyed in the destructor
404 // or you'll get a nasty surprise when you run the incognito tests.
405 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
406 profile_
->GetPrefs());
408 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
409 instant_controller_
.reset(new BrowserInstantController(this));
411 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
413 ProfileMetrics::LogProfileLaunch(profile_
);
415 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
417 // Create the extension window controller before sending notifications.
418 extension_window_controller_
.reset(
419 new BrowserExtensionWindowController(this));
421 SessionService
* session_service
=
422 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
424 session_service
->WindowOpened(this);
426 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
427 // replace uses of this with BL's notifications.
428 content::NotificationService::current()->Notify(
429 chrome::NOTIFICATION_BROWSER_WINDOW_READY
,
430 content::Source
<Browser
>(this),
431 content::NotificationService::NoDetails());
433 // TODO(beng): move to ChromeBrowserMain:
434 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
436 // Notify PDM that this is a first run.
437 ImportAutofillDataWin(
438 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
439 #endif // defined(OS_WIN)
442 fullscreen_controller_
.reset(new FullscreenController(this));
445 Browser::~Browser() {
446 // The tab strip should not have any tabs at this point.
447 if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers())
448 DCHECK(tab_strip_model_
->empty());
450 tab_strip_model_
->RemoveObserver(this);
452 // Destroy the BrowserCommandController before removing the browser, so that
453 // it doesn't act on any notifications that are sent as a result of removing
455 command_controller_
.reset();
456 BrowserList::RemoveBrowser(this);
458 SessionService
* session_service
=
459 SessionServiceFactory::GetForProfile(profile_
);
461 session_service
->WindowClosed(session_id_
);
463 TabRestoreService
* tab_restore_service
=
464 TabRestoreServiceFactory::GetForProfile(profile());
465 if (tab_restore_service
)
466 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
468 #if !defined(OS_MACOSX)
469 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
470 // We're the last browser window with this profile. We need to nuke the
471 // TabRestoreService, which will start the shutdown of the
472 // NavigationControllers and allow for proper shutdown. If we don't do this
473 // chrome won't shutdown cleanly, and may end up crashing when some
474 // thread tries to use the IO thread (or another thread) that is no longer
476 // This isn't a valid assumption for Mac OS, as it stays running after
477 // the last browser has closed. The Mac equivalent is in its app
479 TabRestoreServiceFactory::ResetForProfile(profile_
);
483 profile_pref_registrar_
.RemoveAll();
485 encoding_auto_detect_
.Destroy();
487 // Destroy BrowserExtensionWindowController before the incognito profile
488 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
489 extension_window_controller_
.reset();
491 // Destroy BrowserInstantController before the incongnito profile is destroyed
492 // because the InstantController destructor depends on this profile.
493 instant_controller_
.reset();
495 if (profile_
->IsOffTheRecord() &&
496 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
497 // An incognito profile is no longer needed, this indirectly frees
498 // its cache and cookies once it gets destroyed at the appropriate time.
499 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
502 // There may be pending file dialogs, we need to tell them that we've gone
503 // away so they don't try and call back to us.
504 if (select_file_dialog_
.get())
505 select_file_dialog_
->ListenerDestroyed();
508 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
509 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
510 !browser_defaults::kBrowserAliveWithNoWindows
) {
511 DownloadService::CancelAllDownloads();
515 ///////////////////////////////////////////////////////////////////////////////
518 FindBarController
* Browser::GetFindBarController() {
519 if (!find_bar_controller_
.get()) {
520 FindBar
* find_bar
= window_
->CreateFindBar();
521 find_bar_controller_
.reset(new FindBarController(find_bar
));
522 find_bar
->SetFindBarController(find_bar_controller_
.get());
523 find_bar_controller_
->ChangeWebContents(
524 tab_strip_model_
->GetActiveWebContents());
525 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
527 return find_bar_controller_
.get();
530 bool Browser::HasFindBarController() const {
531 return find_bar_controller_
.get() != NULL
;
534 bool Browser::is_app() const {
535 return !app_name_
.empty();
538 bool Browser::is_devtools() const {
539 return app_name_
== DevToolsWindow::kDevToolsApp
;
542 ///////////////////////////////////////////////////////////////////////////////
543 // Browser, State Storage and Retrieval for UI:
545 gfx::Image
Browser::GetCurrentPageIcon() const {
546 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
547 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
548 // window during the window's creation (before tabs have been added).
549 FaviconTabHelper
* favicon_tab_helper
=
550 web_contents
? FaviconTabHelper::FromWebContents(web_contents
) : NULL
;
551 return favicon_tab_helper
? favicon_tab_helper
->GetFavicon() : gfx::Image();
554 base::string16
Browser::GetWindowTitleForCurrentTab() const {
555 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
556 base::string16 title
;
558 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
559 // window during the window's creation (before tabs have been added).
561 title
= contents
->GetTitle();
562 FormatTitleForDisplay(&title
);
565 title
= CoreTabHelper::GetDefaultTitle();
567 #if defined(OS_MACOSX)
568 // On Mac, we don't want to suffix the page title with
569 // the application name.
571 #elif defined(USE_ASH)
572 // On Ash, we don't want to suffix the page title with the application name,
573 // but on Windows, where USE_ASH can also be true, we still want the prefix
575 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
578 // Don't append the app name to window titles on app frames and app popups
581 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
585 void Browser::FormatTitleForDisplay(base::string16
* title
) {
586 size_t current_index
= 0;
588 while ((match_index
= title
->find(L
'\n', current_index
)) !=
589 base::string16::npos
) {
590 title
->replace(match_index
, 1, base::string16());
591 current_index
= match_index
;
595 ///////////////////////////////////////////////////////////////////////////////
596 // Browser, OnBeforeUnload handling:
598 bool Browser::ShouldCloseWindow() {
599 if (!CanCloseWithInProgressDownloads())
602 if (IsFastTabUnloadEnabled())
603 return fast_unload_controller_
->ShouldCloseWindow();
604 return unload_controller_
->ShouldCloseWindow();
607 bool Browser::CallBeforeUnloadHandlers(
608 const base::Callback
<void(bool)>& on_close_confirmed
) {
609 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
610 if (IsFastTabUnloadEnabled()) {
611 return fast_unload_controller_
->CallBeforeUnloadHandlers(
614 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
617 void Browser::ResetBeforeUnloadHandlers() {
618 cancel_download_confirmation_state_
= NOT_PROMPTED
;
619 if (IsFastTabUnloadEnabled())
620 fast_unload_controller_
->ResetBeforeUnloadHandlers();
622 unload_controller_
->ResetBeforeUnloadHandlers();
625 bool Browser::HasCompletedUnloadProcessing() const {
626 DCHECK(IsFastTabUnloadEnabled());
627 return fast_unload_controller_
->HasCompletedUnloadProcessing();
630 bool Browser::IsAttemptingToCloseBrowser() const {
631 if (IsFastTabUnloadEnabled())
632 return fast_unload_controller_
->is_attempting_to_close_browser();
633 return unload_controller_
->is_attempting_to_close_browser();
636 void Browser::OnWindowClosing() {
637 if (!ShouldCloseWindow())
640 // Application should shutdown on last window close if the user is explicitly
641 // trying to quit, or if there is nothing keeping the browser alive (such as
642 // AppController on the Mac, or BackgroundContentsService for background
644 bool should_quit_if_last_browser
=
645 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
647 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this))
648 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
650 // Don't use GetForProfileIfExisting here, we want to force creation of the
651 // session service so that user can restore what was open.
652 SessionService
* session_service
=
653 SessionServiceFactory::GetForProfile(profile());
655 session_service
->WindowClosing(session_id());
657 TabRestoreService
* tab_restore_service
=
658 TabRestoreServiceFactory::GetForProfile(profile());
660 #if defined(USE_AURA)
661 if (tab_restore_service
&& is_app() && !is_devtools())
662 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
665 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
666 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
668 // TODO(sky): convert session/tab restore to use notification.
669 content::NotificationService::current()->Notify(
670 chrome::NOTIFICATION_BROWSER_CLOSING
,
671 content::Source
<Browser
>(this),
672 content::NotificationService::NoDetails());
674 if (!IsFastTabUnloadEnabled())
675 tab_strip_model_
->CloseAllTabs();
678 ////////////////////////////////////////////////////////////////////////////////
679 // In-progress download termination handling:
681 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
682 if (cancel_downloads
) {
683 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
684 chrome::CloseWindow(this);
688 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
689 // close again we'll show the warning again.
690 cancel_download_confirmation_state_
= NOT_PROMPTED
;
692 // Show the download page so the user can figure-out what downloads are still
694 chrome::ShowDownloads(this);
697 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
698 int* num_downloads_blocking
) const {
699 DCHECK(num_downloads_blocking
);
700 *num_downloads_blocking
= 0;
702 // If we're not running a full browser process with a profile manager
703 // (testing), it's ok to close the browser.
704 if (!g_browser_process
->profile_manager())
705 return DOWNLOAD_CLOSE_OK
;
707 int total_download_count
=
708 DownloadService::NonMaliciousDownloadCountAllProfiles();
709 if (total_download_count
== 0)
710 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
712 // Figure out how many windows are open total, and associated with this
713 // profile, that are relevant for the ok-to-close decision.
714 int profile_window_count
= 0;
715 int total_window_count
= 0;
716 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
717 // Don't count this browser window or any other in the process of closing.
718 Browser
* const browser
= *it
;
719 // Window closing may be delayed, and windows that are in the process of
720 // closing don't count against our totals.
721 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
724 if (it
->profile() == profile())
725 profile_window_count
++;
726 total_window_count
++;
729 // If there aren't any other windows, we're at browser shutdown,
730 // which would cancel all current downloads.
731 if (total_window_count
== 0) {
732 *num_downloads_blocking
= total_download_count
;
733 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
736 // If there aren't any other windows on our profile, and we're an incognito
737 // profile, and there are downloads associated with that profile,
738 // those downloads would be cancelled by our window (-> profile) close.
739 DownloadService
* download_service
=
740 DownloadServiceFactory::GetForBrowserContext(profile());
741 if ((profile_window_count
== 0) &&
742 (download_service
->NonMaliciousDownloadCount() > 0) &&
743 profile()->IsOffTheRecord()) {
744 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
745 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
748 // Those are the only conditions under which we will block shutdown.
749 return DOWNLOAD_CLOSE_OK
;
752 ////////////////////////////////////////////////////////////////////////////////
753 // Browser, Tab adding/showing functions:
755 void Browser::WindowFullscreenStateChanged() {
756 fullscreen_controller_
->WindowFullscreenStateChanged();
757 command_controller_
->FullscreenStateChanged();
758 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
761 void Browser::VisibleSSLStateChanged(content::WebContents
* web_contents
) {
762 // When the current tab's SSL state changes, we need to update the URL
763 // bar to reflect the new state.
764 DCHECK(web_contents
);
765 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
766 UpdateToolbar(false);
769 void Browser::OnWebContentsInstantSupportDisabled(
770 const content::WebContents
* web_contents
) {
771 DCHECK(web_contents
);
772 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
773 UpdateToolbar(false);
776 ///////////////////////////////////////////////////////////////////////////////
777 // Browser, Assorted browser commands:
779 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
780 fullscreen_controller_
->ToggleFullscreenModeWithExtension(extension_url
);
783 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
784 return SupportsWindowFeatureImpl(feature
, true);
787 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
788 return SupportsWindowFeatureImpl(feature
, false);
791 void Browser::ToggleEncodingAutoDetect() {
792 content::RecordAction(UserMetricsAction("AutoDetectChange"));
793 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
794 // If "auto detect" is turned on, then any current override encoding
795 // is cleared. This also implicitly performs a reload.
796 // OTOH, if "auto detect" is turned off, we don't change the currently
798 if (encoding_auto_detect_
.GetValue()) {
799 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
801 contents
->ResetOverrideEncoding();
805 void Browser::OverrideEncoding(int encoding_id
) {
806 content::RecordAction(UserMetricsAction("OverrideEncoding"));
807 const std::string selected_encoding
=
808 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
809 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
810 if (!selected_encoding
.empty() && contents
)
811 contents
->SetOverrideEncoding(selected_encoding
);
812 // Update the list of recently selected encodings.
813 std::string new_selected_encoding_list
;
814 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
815 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
817 &new_selected_encoding_list
)) {
818 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
819 new_selected_encoding_list
);
823 void Browser::OpenFile() {
824 content::RecordAction(UserMetricsAction("OpenFile"));
825 select_file_dialog_
= ui::SelectFileDialog::Create(
826 this, new ChromeSelectFilePolicy(
827 tab_strip_model_
->GetActiveWebContents()));
829 const base::FilePath directory
= profile_
->last_selected_directory();
831 // TODO(beng): figure out how to juggle this.
832 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
833 ui::SelectFileDialog::FileTypeInfo file_types
;
834 file_types
.support_drive
= true;
835 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
840 base::FilePath::StringType(),
845 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
846 if (GetStatusBubble())
847 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
850 ///////////////////////////////////////////////////////////////////////////////
852 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
853 content::PageTransition transition
,
854 bool user_initiated
) {
855 tab_strip_model_
->TabNavigating(contents
, transition
);
857 bool contents_is_selected
=
858 contents
== tab_strip_model_
->GetActiveWebContents();
859 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
860 // Forcibly reset the location bar if the url is going to change in the
861 // current tab, since otherwise it won't discard any ongoing user edits,
862 // since it doesn't realize this is a user-initiated action.
863 window()->GetLocationBar()->Revert();
866 if (GetStatusBubble())
867 GetStatusBubble()->Hide();
869 // Update the location bar. This is synchronous. We specifically don't
870 // update the load state since the load hasn't started yet and updating it
871 // will put it out of sync with the actual state like whether we're
872 // displaying a favicon, which controls the throbber. If we updated it here,
873 // the throbber will show the default favicon for a split second when
874 // navigating away from the new tab page.
875 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
877 if (contents_is_selected
)
878 contents
->GetView()->SetInitialFocus();
881 ///////////////////////////////////////////////////////////////////////////////
882 // Browser, PageNavigator implementation:
884 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
885 return OpenURLFromTab(NULL
, params
);
888 ///////////////////////////////////////////////////////////////////////////////
889 // Browser, TabStripModelObserver implementation:
891 void Browser::TabInsertedAt(WebContents
* contents
,
894 SetAsDelegate(contents
, this);
895 SessionTabHelper
* session_tab_helper
=
896 SessionTabHelper::FromWebContents(contents
);
897 session_tab_helper
->SetWindowID(session_id());
899 content::NotificationService::current()->Notify(
900 chrome::NOTIFICATION_TAB_PARENTED
,
901 content::Source
<content::WebContents
>(contents
),
902 content::NotificationService::NoDetails());
904 SyncHistoryWithTabs(index
);
906 // Make sure the loading state is updated correctly, otherwise the throbber
907 // won't start if the page is loading.
908 LoadingStateChanged(contents
);
910 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
912 SessionService
* session_service
=
913 SessionServiceFactory::GetForProfile(profile_
);
914 if (session_service
) {
915 session_service
->TabInserted(contents
);
916 int new_active_index
= tab_strip_model_
->active_index();
917 if (index
< new_active_index
)
918 session_service
->SetSelectedTabInWindow(session_id(),
923 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
924 WebContents
* contents
,
926 fullscreen_controller_
->OnTabClosing(contents
);
927 SessionService
* session_service
=
928 SessionServiceFactory::GetForProfile(profile_
);
930 session_service
->TabClosing(contents
);
931 content::NotificationService::current()->Notify(
932 chrome::NOTIFICATION_TAB_CLOSING
,
933 content::Source
<NavigationController
>(&contents
->GetController()),
934 content::NotificationService::NoDetails());
936 // Sever the WebContents' connection back to us.
937 SetAsDelegate(contents
, NULL
);
940 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
941 // TabDetachedAt is called before TabStripModel has updated the
943 int old_active_index
= tab_strip_model_
->active_index();
944 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
945 SessionService
* session_service
=
946 SessionServiceFactory::GetForProfileIfExisting(profile_
);
948 session_service
->SetSelectedTabInWindow(session_id(),
949 old_active_index
- 1);
951 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
954 void Browser::TabDeactivated(WebContents
* contents
) {
955 fullscreen_controller_
->OnTabDeactivated(contents
);
956 search_delegate_
->OnTabDeactivated(contents
);
957 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
959 // Save what the user's currently typing, so it can be restored when we
960 // switch back to this tab.
961 window_
->GetLocationBar()->SaveStateToContents(contents
);
963 if (instant_controller_
)
964 instant_controller_
->TabDeactivated(contents
);
967 void Browser::ActiveTabChanged(WebContents
* old_contents
,
968 WebContents
* new_contents
,
971 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
973 // Update the bookmark state, since the BrowserWindow may query it during
974 // OnActiveTabChanged() below.
975 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
977 // Let the BrowserWindow do its handling. On e.g. views this changes the
978 // focused object, which should happen before we update the toolbar below,
979 // since the omnibox expects the correct element to already be focused when it
981 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
983 // Discarded tabs always get reloaded.
984 if (tab_strip_model_
->IsTabDiscarded(index
)) {
985 LOG(WARNING
) << "Reloading discarded tab at " << index
;
986 static int reload_count
= 0;
987 UMA_HISTOGRAM_CUSTOM_COUNTS(
988 "Tabs.Discard.ReloadCount", ++reload_count
, 1, 1000, 50);
989 chrome::Reload(this, CURRENT_TAB
);
992 // If we have any update pending, do it now.
993 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
994 ProcessPendingUIUpdates();
996 // Propagate the profile to the location bar.
997 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
999 if (chrome::IsInstantExtendedAPIEnabled())
1000 search_delegate_
->OnTabActivated(new_contents
);
1002 // Update reload/stop state.
1003 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1005 // Update commands to reflect current state.
1006 command_controller_
->TabStateChanged();
1008 // Reset the status bubble.
1009 StatusBubble
* status_bubble
= GetStatusBubble();
1010 if (status_bubble
) {
1011 status_bubble
->Hide();
1013 // Show the loading state (if any).
1014 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1015 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1018 if (HasFindBarController()) {
1019 find_bar_controller_
->ChangeWebContents(new_contents
);
1020 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1023 // Update sessions. Don't force creation of sessions. If sessions doesn't
1024 // exist, the change will be picked up by sessions when created.
1025 SessionService
* session_service
=
1026 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1027 if (session_service
&& !tab_strip_model_
->closing_all()) {
1028 session_service
->SetSelectedTabInWindow(session_id(),
1029 tab_strip_model_
->active_index());
1032 // This needs to be called after notifying SearchDelegate.
1033 if (instant_controller_
)
1034 instant_controller_
->ActiveTabChanged();
1036 autofill::TabAutofillManagerDelegate::FromWebContents(new_contents
)->
1038 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1041 void Browser::TabMoved(WebContents
* contents
,
1044 DCHECK(from_index
>= 0 && to_index
>= 0);
1045 // Notify the history service.
1046 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1049 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1050 WebContents
* old_contents
,
1051 WebContents
* new_contents
,
1053 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1054 fullscreen_controller_
->OnTabClosing(old_contents
);
1055 SessionService
* session_service
=
1056 SessionServiceFactory::GetForProfile(profile_
);
1057 if (session_service
)
1058 session_service
->TabClosing(old_contents
);
1059 TabInsertedAt(new_contents
,
1061 (index
== tab_strip_model_
->active_index()));
1063 int entry_count
= new_contents
->GetController().GetEntryCount();
1064 if (entry_count
> 0) {
1065 // Send out notification so that observers are updated appropriately.
1066 new_contents
->GetController().NotifyEntryChanged(
1067 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1),
1071 if (session_service
) {
1072 // The new_contents may end up with a different navigation stack. Force
1073 // the session service to update itself.
1074 session_service
->TabRestored(new_contents
,
1075 tab_strip_model_
->IsTabPinned(index
));
1079 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1080 SessionService
* session_service
=
1081 SessionServiceFactory::GetForProfileIfExisting(profile());
1082 if (session_service
) {
1083 SessionTabHelper
* session_tab_helper
=
1084 SessionTabHelper::FromWebContents(contents
);
1085 session_service
->SetPinnedState(session_id(),
1086 session_tab_helper
->session_id(),
1087 tab_strip_model_
->IsTabPinned(index
));
1091 void Browser::TabStripEmpty() {
1092 // Close the frame after we return to the message loop (not immediately,
1093 // otherwise it will destroy this object before the stack has a chance to
1095 // Note: This will be called several times if TabStripEmpty is called several
1096 // times. This is because it does not close the window if tabs are
1098 base::MessageLoop::current()->PostTask(
1099 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1101 // Instant may have visible WebContents that need to be detached before the
1102 // window system closes.
1103 instant_controller_
.reset();
1106 bool Browser::CanOverscrollContent() const {
1107 #if defined(USE_AURA)
1108 bool overscroll_enabled
= CommandLine::ForCurrentProcess()->
1109 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation
) != "0";
1110 if (!overscroll_enabled
)
1112 if (is_app() || is_devtools() || !is_type_tabbed())
1115 // The detached bookmark bar has appearance of floating above the
1116 // web-contents. This does not play nicely with overscroll navigation
1117 // gestures. So disable overscroll navigation when the bookmark bar is in the
1119 if (bookmark_bar_state_
== BookmarkBar::DETACHED
)
1127 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1128 const NativeWebKeyboardEvent
& event
,
1129 bool* is_keyboard_shortcut
) {
1130 // Escape exits tabbed fullscreen mode.
1131 // TODO(koz): Write a test for this http://crbug.com/100441.
1132 if (event
.windowsKeyCode
== 27 &&
1133 fullscreen_controller_
->HandleUserPressedEscape()) {
1136 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1139 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1140 const NativeWebKeyboardEvent
& event
) {
1141 window()->HandleKeyboardEvent(event
);
1144 bool Browser::TabsNeedBeforeUnloadFired() {
1145 if (IsFastTabUnloadEnabled())
1146 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1147 return unload_controller_
->TabsNeedBeforeUnloadFired();
1150 void Browser::OverscrollUpdate(int delta_y
) {
1151 window_
->OverscrollUpdate(delta_y
);
1154 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1155 const gfx::Rect
& anchor_in_root_view
,
1156 const base::string16
& main_text
,
1157 const base::string16
& sub_text
) {
1158 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1160 validation_message_bubble_
=
1161 chrome::ValidationMessageBubble::CreateAndShow(
1162 rwhv
->GetRenderWidgetHost(),
1163 anchor_in_root_view
,
1169 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1170 validation_message_bubble_
.reset();
1173 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1174 const gfx::Rect
& anchor_in_root_view
) {
1175 if (!validation_message_bubble_
)
1177 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1179 validation_message_bubble_
->SetPositionRelativeToAnchor(
1180 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1184 bool Browser::IsMouseLocked() const {
1185 return fullscreen_controller_
->IsMouseLocked();
1188 void Browser::OnWindowDidShow() {
1189 if (window_has_shown_
)
1191 window_has_shown_
= true;
1193 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1194 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1195 // Measure the latency from startup till the first browser window becomes
1197 static bool is_first_browser_window
= true;
1198 if (is_first_browser_window
&&
1199 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1200 is_first_browser_window
= false;
1201 const base::Time process_creation_time
=
1202 base::CurrentProcessInfo::CreationTime();
1204 if (!process_creation_time
.is_null()) {
1205 UMA_HISTOGRAM_LONG_TIMES(
1206 "Startup.BrowserWindowDisplay",
1207 base::Time::Now() - process_creation_time
);
1210 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1212 // Nothing to do for non-tabbed windows.
1213 if (!is_type_tabbed())
1216 // Show any pending global error bubble.
1217 GlobalErrorService
* service
=
1218 GlobalErrorServiceFactory::GetForProfile(profile());
1219 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1221 error
->ShowBubbleView(this);
1224 void Browser::ShowFirstRunBubble() {
1225 window()->GetLocationBar()->ShowFirstRunBubble();
1228 void Browser::ShowDownload(content::DownloadItem
* download
) {
1232 // If the download occurs in a new tab, and it's not a save page
1233 // download (started before initial navigation completed) close it.
1234 WebContents
* source
= download
->GetWebContents();
1235 if (source
&& source
->GetController().IsInitialNavigation() &&
1236 tab_strip_model_
->count() > 1 && !download
->IsSavePackageDownload()) {
1237 CloseContents(source
);
1240 // Some (app downloads) are not supposed to appear on the shelf.
1241 if (!DownloadItemModel(download
).ShouldShowInShelf())
1244 // GetDownloadShelf creates the download shelf if it was not yet created.
1245 DownloadShelf
* shelf
= window()->GetDownloadShelf();
1246 shelf
->AddDownload(download
);
1249 ///////////////////////////////////////////////////////////////////////////////
1250 // Browser, content::WebContentsDelegate implementation:
1252 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1253 const OpenURLParams
& params
) {
1254 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1255 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1256 nav_params
.source_contents
= source
;
1257 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1258 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1259 nav_params
.user_gesture
= params
.user_gesture
;
1261 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1263 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1265 if (popup_blocker_helper
) {
1266 if ((params
.disposition
== NEW_POPUP
||
1267 params
.disposition
== NEW_FOREGROUND_TAB
||
1268 params
.disposition
== NEW_BACKGROUND_TAB
||
1269 params
.disposition
== NEW_WINDOW
) &&
1270 !params
.user_gesture
&& !CommandLine::ForCurrentProcess()->HasSwitch(
1271 switches::kDisablePopupBlocking
)) {
1272 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1273 WebWindowFeatures())) {
1279 chrome::Navigate(&nav_params
);
1281 return nav_params
.target_contents
;
1284 void Browser::NavigationStateChanged(const WebContents
* source
,
1285 unsigned changed_flags
) {
1286 // Only update the UI when something visible has changed.
1288 ScheduleUIUpdate(source
, changed_flags
);
1290 // We can synchronously update commands since they will only change once per
1291 // navigation, so we don't have to worry about flickering. We do, however,
1292 // need to update the command state early on load to always present usable
1293 // actions in the face of slow-to-commit pages.
1294 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1295 content::INVALIDATE_TYPE_LOAD
))
1296 command_controller_
->TabStateChanged();
1299 void Browser::AddNewContents(WebContents
* source
,
1300 WebContents
* new_contents
,
1301 WindowOpenDisposition disposition
,
1302 const gfx::Rect
& initial_pos
,
1304 bool* was_blocked
) {
1305 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_pos
,
1306 user_gesture
, was_blocked
);
1309 void Browser::ActivateContents(WebContents
* contents
) {
1310 tab_strip_model_
->ActivateTabAt(
1311 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1312 window_
->Activate();
1315 void Browser::DeactivateContents(WebContents
* contents
) {
1316 window_
->Deactivate();
1319 void Browser::LoadingStateChanged(WebContents
* source
) {
1320 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1321 window_
->UpdateTitleBar();
1323 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1324 if (source
== selected_contents
) {
1325 bool is_loading
= source
->IsLoading();
1326 command_controller_
->LoadingStateChanged(is_loading
, false);
1327 if (GetStatusBubble()) {
1328 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1329 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1334 void Browser::CloseContents(WebContents
* source
) {
1335 bool can_close_contents
;
1336 if (IsFastTabUnloadEnabled())
1337 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1339 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1341 if (can_close_contents
)
1342 chrome::CloseWebContents(this, source
, true);
1345 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1346 if (!IsPopupOrPanel(source
)) {
1347 NOTREACHED() << "moving invalid browser type";
1350 window_
->SetBounds(pos
);
1353 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1354 return is_type_popup();
1357 void Browser::UpdateTargetURL(WebContents
* source
, int32 page_id
,
1359 if (!GetStatusBubble())
1362 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1363 PrefService
* prefs
= profile_
->GetPrefs();
1364 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1368 void Browser::ContentsMouseEvent(
1369 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1370 if (!GetStatusBubble())
1373 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1374 GetStatusBubble()->MouseMoved(location
, !motion
);
1376 GetStatusBubble()->SetURL(GURL(), std::string());
1380 void Browser::ContentsZoomChange(bool zoom_in
) {
1381 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1384 void Browser::WebContentsFocused(WebContents
* contents
) {
1385 window_
->WebContentsFocused(contents
);
1388 bool Browser::TakeFocus(content::WebContents
* source
,
1390 content::NotificationService::current()->Notify(
1391 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1392 content::Source
<Browser
>(this),
1393 content::NotificationService::NoDetails());
1397 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1398 return window_
->GetRootWindowResizerRect();
1401 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1403 bool* proceed_to_fire_unload
) {
1404 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1405 proceed
, proceed_to_fire_unload
))
1408 if (IsFastTabUnloadEnabled()) {
1409 *proceed_to_fire_unload
=
1410 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1412 *proceed_to_fire_unload
=
1413 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1417 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1418 const content::NavigationEntry
* entry
=
1419 source
->GetController().GetActiveEntry();
1421 GURL url
= entry
->GetURL();
1422 GURL virtual_url
= entry
->GetVirtualURL();
1423 if ((url
.SchemeIs(chrome::kChromeUIScheme
) &&
1424 url
.host() == chrome::kChromeUINewTabHost
) ||
1425 (virtual_url
.SchemeIs(chrome::kChromeUIScheme
) &&
1426 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1431 return chrome::NavEntryIsInstantNTP(source
, entry
);
1434 void Browser::SetFocusToLocationBar(bool select_all
) {
1435 // Two differences between this and FocusLocationBar():
1436 // (1) This doesn't get recorded in user metrics, since it's called
1438 // (2) This checks whether the location bar can be focused, and if not, clears
1439 // the focus. FocusLocationBar() is only reached when the location bar is
1440 // focusable, but this may be reached at other times, e.g. while in
1441 // fullscreen mode, where we need to leave focus in a consistent state.
1442 window_
->SetFocusToLocationBar(select_all
);
1445 int Browser::GetExtraRenderViewHeight() const {
1446 return window_
->GetExtraRenderViewHeight();
1449 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1451 chrome::ViewSource(this, source
);
1454 void Browser::ViewSourceForFrame(WebContents
* source
,
1455 const GURL
& frame_url
,
1456 const content::PageState
& frame_page_state
) {
1458 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1461 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1462 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1466 bool Browser::ShouldCreateWebContents(
1467 WebContents
* web_contents
,
1469 WindowContainerType window_container_type
,
1470 const base::string16
& frame_name
,
1471 const GURL
& target_url
,
1472 const std::string
& partition_id
,
1473 content::SessionStorageNamespace
* session_storage_namespace
) {
1474 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1475 // If a BackgroundContents is created, suppress the normal WebContents.
1476 return !MaybeCreateBackgroundContents(route_id
,
1481 session_storage_namespace
);
1487 void Browser::WebContentsCreated(WebContents
* source_contents
,
1488 int64 source_frame_id
,
1489 const base::string16
& frame_name
,
1490 const GURL
& target_url
,
1491 WebContents
* new_contents
) {
1492 // Adopt the WebContents now, so all observers are in place, as the network
1493 // requests for its initial navigation will start immediately. The WebContents
1494 // will later be inserted into this browser using Browser::Navigate via
1496 BrowserTabContents::AttachTabHelpers(new_contents
);
1499 RetargetingDetails details
;
1500 details
.source_web_contents
= source_contents
;
1501 details
.source_frame_id
= source_frame_id
;
1502 details
.target_url
= target_url
;
1503 details
.target_web_contents
= new_contents
;
1504 details
.not_yet_in_tabstrip
= true;
1505 content::NotificationService::current()->Notify(
1506 chrome::NOTIFICATION_RETARGETING
,
1507 content::Source
<Profile
>(profile_
),
1508 content::Details
<RetargetingDetails
>(&details
));
1511 void Browser::RendererUnresponsive(WebContents
* source
) {
1512 // Ignore hangs if a tab is blocked.
1513 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1514 DCHECK_NE(TabStripModel::kNoTab
, index
);
1515 if (tab_strip_model_
->IsTabBlocked(index
))
1518 chrome::ShowHungRendererDialog(source
);
1521 void Browser::RendererResponsive(WebContents
* source
) {
1522 chrome::HideHungRendererDialog(source
);
1525 void Browser::WorkerCrashed(WebContents
* source
) {
1526 SimpleAlertInfoBarDelegate::Create(
1527 InfoBarService::FromWebContents(source
), InfoBarDelegate::kNoIconID
,
1528 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT
), true);
1531 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1532 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1533 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1536 void Browser::DidNavigateToPendingEntry(WebContents
* web_contents
) {
1537 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1538 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1541 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager() {
1542 return GetJavaScriptDialogManagerInstance();
1545 content::ColorChooser
* Browser::OpenColorChooser(
1546 WebContents
* web_contents
,
1547 SkColor initial_color
,
1548 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1549 return chrome::ShowColorChooser(web_contents
, initial_color
);
1552 void Browser::RunFileChooser(WebContents
* web_contents
,
1553 const content::FileChooserParams
& params
) {
1554 FileSelectHelper::RunFileChooser(web_contents
, params
);
1557 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1559 const base::FilePath
& path
) {
1560 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1563 bool Browser::EmbedsFullscreenWidget() const {
1564 return CommandLine::ForCurrentProcess()->
1565 HasSwitch(switches::kEmbedFlashFullscreen
);
1568 void Browser::ToggleFullscreenModeForTab(WebContents
* web_contents
,
1569 bool enter_fullscreen
) {
1570 fullscreen_controller_
->ToggleFullscreenModeForTab(web_contents
,
1574 bool Browser::IsFullscreenForTabOrPending(
1575 const WebContents
* web_contents
) const {
1576 return fullscreen_controller_
->IsFullscreenForTabOrPending(web_contents
);
1579 void Browser::JSOutOfMemory(WebContents
* web_contents
) {
1580 InfoBarService
* infobar_service
=
1581 InfoBarService::FromWebContents(web_contents
);
1582 if (!infobar_service
)
1584 SimpleAlertInfoBarDelegate::Create(
1585 infobar_service
, InfoBarDelegate::kNoIconID
,
1586 l10n_util::GetStringUTF16(IDS_JS_OUT_OF_MEMORY_PROMPT
), true);
1589 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1590 const std::string
& protocol
,
1592 const base::string16
& title
,
1593 bool user_gesture
) {
1595 Profile::FromBrowserContext(web_contents
->GetBrowserContext());
1596 if (profile
->IsOffTheRecord())
1599 ProtocolHandler handler
=
1600 ProtocolHandler::CreateProtocolHandler(protocol
, url
, title
);
1602 ProtocolHandlerRegistry
* registry
=
1603 ProtocolHandlerRegistryFactory::GetForProfile(profile
);
1604 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1607 TabSpecificContentSettings
* tab_content_settings
=
1608 TabSpecificContentSettings::FromWebContents(web_contents
);
1609 if (!user_gesture
&& window_
) {
1610 tab_content_settings
->set_pending_protocol_handler(handler
);
1611 tab_content_settings
->set_previous_protocol_handler(
1612 registry
->GetHandlerFor(handler
.protocol()));
1613 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1617 // Make sure content-setting icon is turned off in case the page does
1618 // ungestured and gestured RPH calls.
1620 tab_content_settings
->ClearPendingProtocolHandler();
1621 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1624 RegisterProtocolHandlerInfoBarDelegate::Create(
1625 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1628 void Browser::UpdatePreferredSize(WebContents
* source
,
1629 const gfx::Size
& pref_size
) {
1630 window_
->UpdatePreferredSize(source
, pref_size
);
1633 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1634 const gfx::Size
& new_size
) {
1635 window_
->ResizeDueToAutoResize(source
, new_size
);
1638 void Browser::FindReply(WebContents
* web_contents
,
1640 int number_of_matches
,
1641 const gfx::Rect
& selection_rect
,
1642 int active_match_ordinal
,
1643 bool final_update
) {
1644 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1645 if (!find_tab_helper
)
1648 find_tab_helper
->HandleFindReply(request_id
,
1651 active_match_ordinal
,
1655 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1657 bool last_unlocked_by_target
) {
1658 fullscreen_controller_
->RequestToLockMouse(web_contents
,
1660 last_unlocked_by_target
);
1663 void Browser::LostMouseLock() {
1664 fullscreen_controller_
->LostMouseLock();
1667 void Browser::RequestMediaAccessPermission(
1668 content::WebContents
* web_contents
,
1669 const content::MediaStreamRequest
& request
,
1670 const content::MediaResponseCallback
& callback
) {
1671 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1674 bool Browser::RequestPpapiBrokerPermission(
1675 WebContents
* web_contents
,
1677 const base::FilePath
& plugin_path
,
1678 const base::Callback
<void(bool)>& callback
) {
1679 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1683 gfx::Size
Browser::GetSizeForNewRenderView(
1684 const WebContents
* web_contents
) const {
1685 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1686 // would disappear on non-NTP pages, resulting in a bigger size for the new
1688 gfx::Size size
= web_contents
->GetView()->GetContainerSize();
1689 // Don't change render view size if bookmark bar is currently not detached,
1690 // or there's no pending entry, or navigating to a NTP page.
1691 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1693 const NavigationEntry
* pending_entry
=
1694 web_contents
->GetController().GetPendingEntry();
1695 if (pending_entry
&&
1696 !chrome::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1698 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1703 ///////////////////////////////////////////////////////////////////////////////
1704 // Browser, CoreTabHelperDelegate implementation:
1706 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1707 content::WebContents
* new_contents
) {
1708 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1709 DCHECK_NE(TabStripModel::kNoTab
, index
);
1710 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1713 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1714 return chrome::CanReload(this);
1717 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1718 return chrome::CanSavePage(this);
1721 ///////////////////////////////////////////////////////////////////////////////
1722 // Browser, SearchEngineTabHelperDelegate implementation:
1724 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1726 window()->ConfirmAddSearchProvider(template_url
, profile
);
1729 ///////////////////////////////////////////////////////////////////////////////
1730 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1732 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
1734 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
1735 if (index
== TabStripModel::kNoTab
) {
1739 tab_strip_model_
->SetTabBlocked(index
, blocked
);
1740 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
1741 web_contents
->GetView()->Focus();
1744 web_modal::WebContentsModalDialogHost
*
1745 Browser::GetWebContentsModalDialogHost() {
1746 return window_
->GetWebContentsModalDialogHost();
1749 ///////////////////////////////////////////////////////////////////////////////
1750 // Browser, BookmarkTabHelperDelegate implementation:
1752 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
1754 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1755 window_
->SetStarredState(starred
);
1758 ///////////////////////////////////////////////////////////////////////////////
1759 // Browser, ZoomObserver implementation:
1761 void Browser::OnZoomChanged(content::WebContents
* source
,
1762 bool can_show_bubble
) {
1763 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1764 // Only show the zoom bubble for zoom changes in the active window.
1765 window_
->ZoomChangedForActiveTab(can_show_bubble
&& window_
->IsActive());
1769 ///////////////////////////////////////////////////////////////////////////////
1770 // Browser, ui::SelectFileDialog::Listener implementation:
1772 void Browser::FileSelected(const base::FilePath
& path
, int index
,
1774 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
1777 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
1780 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
1782 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
1784 #if defined(OS_CHROMEOS)
1785 drive::util::MaybeSetDriveURL(profile_
, file_info
.file_path
, &url
);
1791 OpenURL(OpenURLParams(
1792 url
, Referrer(), CURRENT_TAB
, content::PAGE_TRANSITION_TYPED
, false));
1795 ///////////////////////////////////////////////////////////////////////////////
1796 // Browser, content::NotificationObserver implementation:
1798 void Browser::Observe(int type
,
1799 const content::NotificationSource
& source
,
1800 const content::NotificationDetails
& details
) {
1802 case chrome::NOTIFICATION_EXTENSION_UNLOADED
: {
1803 if (window()->GetLocationBar())
1804 window()->GetLocationBar()->UpdatePageActions();
1806 const extensions::UnloadedExtensionInfo
* extension_info
=
1807 content::Details
<extensions::UnloadedExtensionInfo
>(details
).ptr();
1809 // Close any tabs from the unloaded extension, unless it's terminated,
1810 // in which case let the sad tabs remain.
1811 if (extension_info
->reason
!=
1812 extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
1813 const Extension
* extension
= extension_info
->extension
;
1814 // Iterate backwards as we may remove items while iterating.
1815 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
1816 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
1817 // Two cases are handled here:
1818 // - The scheme check is for when an extension page is loaded in a
1819 // tab, e.g. chrome-extension://id/page.html.
1820 // - The extension_app check is for apps, which can have non-extension
1821 // schemes, e.g. https://mail.google.com if you have the Gmail app
1823 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
1824 web_contents
->GetURL().host() == extension
->id()) ||
1825 (extensions::TabHelper::FromWebContents(
1826 web_contents
)->extension_app() == extension
)) {
1827 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
1834 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
1835 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
1836 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
1837 window()->GetLocationBar()->InvalidatePageActions();
1841 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED
:
1842 case chrome::NOTIFICATION_EXTENSION_LOADED
:
1843 // During window creation on Windows we may end up calling into
1844 // SHAppBarMessage, which internally spawns a nested message loop. This
1845 // makes it possible for us to end up here before window creation has
1846 // completed, at which point window_ is NULL. See 94752 for details.
1847 if (window() && window()->GetLocationBar())
1848 window()->GetLocationBar()->UpdatePageActions();
1851 #if defined(ENABLE_THEMES)
1852 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
1853 window()->UserChangedTheme();
1857 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
1858 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
1859 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
1860 LocationBar
* location_bar
= window()->GetLocationBar();
1862 location_bar
->UpdateContentSettingsIcons();
1868 NOTREACHED() << "Got a notification we didn't register for.";
1872 ///////////////////////////////////////////////////////////////////////////////
1873 // Browser, Command and state updating (private):
1875 void Browser::OnDevToolsDisabledChanged() {
1876 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
1877 content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1880 ///////////////////////////////////////////////////////////////////////////////
1881 // Browser, UI update coalescing and handling (private):
1883 void Browser::UpdateToolbar(bool should_restore_state
) {
1884 window_
->UpdateToolbar(should_restore_state
?
1885 tab_strip_model_
->GetActiveWebContents() : NULL
);
1888 void Browser::ScheduleUIUpdate(const WebContents
* source
,
1889 unsigned changed_flags
) {
1891 if (DevToolsWindow::IsDevToolsWindow(source
->GetRenderViewHost()))
1894 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1895 DCHECK_NE(TabStripModel::kNoTab
, index
);
1897 // Do some synchronous updates.
1898 if (changed_flags
& content::INVALIDATE_TYPE_URL
&&
1899 source
== tab_strip_model_
->GetActiveWebContents()) {
1900 // Only update the URL for the current tab. Note that we do not update
1901 // the navigation commands since those would have already been updated
1902 // synchronously by NavigationStateChanged.
1903 UpdateToolbar(false);
1904 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
1906 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
1907 // Update the loading state synchronously. This is so the throbber will
1908 // immediately start/stop, which gives a more snappy feel. We want to do
1909 // this for any tab so they start & stop quickly.
1910 tab_strip_model_
->UpdateWebContentsStateAt(
1911 tab_strip_model_
->GetIndexOfWebContents(source
),
1912 TabStripModelObserver::LOADING_ONLY
);
1913 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
1914 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
1918 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
1919 // To correctly calculate whether the title changed while not loading
1920 // we need to process the update synchronously. This state only matters for
1921 // the TabStripModel, so we notify the TabStripModel now and notify others
1923 tab_strip_model_
->UpdateWebContentsStateAt(
1924 tab_strip_model_
->GetIndexOfWebContents(source
),
1925 TabStripModelObserver::TITLE_NOT_LOADING
);
1928 // If the only updates were synchronously handled above, we're done.
1929 if (changed_flags
== 0)
1932 // Save the dirty bits.
1933 scheduled_updates_
[source
] |= changed_flags
;
1935 if (!chrome_updater_factory_
.HasWeakPtrs()) {
1936 // No task currently scheduled, start another.
1937 base::MessageLoop::current()->PostDelayedTask(
1939 base::Bind(&Browser::ProcessPendingUIUpdates
,
1940 chrome_updater_factory_
.GetWeakPtr()),
1941 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
1945 void Browser::ProcessPendingUIUpdates() {
1947 // Validate that all tabs we have pending updates for exist. This is scary
1948 // because the pending list must be kept in sync with any detached or
1950 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
1951 i
!= scheduled_updates_
.end(); ++i
) {
1953 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
1954 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
1963 chrome_updater_factory_
.InvalidateWeakPtrs();
1965 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
1966 i
!= scheduled_updates_
.end(); ++i
) {
1967 // Do not dereference |contents|, it may be out-of-date!
1968 const WebContents
* contents
= i
->first
;
1969 unsigned flags
= i
->second
;
1971 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
1972 // Updates that only matter when the tab is selected go here.
1974 if (flags
& content::INVALIDATE_TYPE_PAGE_ACTIONS
) {
1975 LocationBar
* location_bar
= window()->GetLocationBar();
1977 location_bar
->UpdatePageActions();
1979 // Updating the URL happens synchronously in ScheduleUIUpdate.
1980 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
1981 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1982 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1985 if (flags
& (content::INVALIDATE_TYPE_TAB
|
1986 content::INVALIDATE_TYPE_TITLE
)) {
1987 window_
->UpdateTitleBar();
1991 // Updates that don't depend upon the selected state go here.
1993 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
1994 tab_strip_model_
->UpdateWebContentsStateAt(
1995 tab_strip_model_
->GetIndexOfWebContents(contents
),
1996 TabStripModelObserver::ALL
);
1999 // Update the bookmark bar. It may happen that the tab is crashed, and if
2000 // so, the bookmark bar should be hidden.
2001 if (flags
& content::INVALIDATE_TYPE_TAB
)
2002 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2004 // We don't need to process INVALIDATE_STATE, since that's not visible.
2007 scheduled_updates_
.clear();
2010 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2014 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2015 if (i
!= scheduled_updates_
.end())
2016 scheduled_updates_
.erase(i
);
2019 ///////////////////////////////////////////////////////////////////////////////
2020 // Browser, Getters for UI (private):
2022 StatusBubble
* Browser::GetStatusBubble() {
2023 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2024 if (chrome::IsRunningInAppMode())
2027 return window_
? window_
->GetStatusBubble() : NULL
;
2030 ///////////////////////////////////////////////////////////////////////////////
2031 // Browser, Session restore functions (private):
2033 void Browser::SyncHistoryWithTabs(int index
) {
2034 SessionService
* session_service
=
2035 SessionServiceFactory::GetForProfileIfExisting(profile());
2036 if (session_service
) {
2037 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2038 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2040 SessionTabHelper
* session_tab_helper
=
2041 SessionTabHelper::FromWebContents(web_contents
);
2042 session_service
->SetTabIndexInWindow(
2043 session_id(), session_tab_helper
->session_id(), i
);
2044 session_service
->SetPinnedState(
2046 session_tab_helper
->session_id(),
2047 tab_strip_model_
->IsTabPinned(i
));
2053 ///////////////////////////////////////////////////////////////////////////////
2054 // Browser, In-progress download termination handling (private):
2056 bool Browser::CanCloseWithInProgressDownloads() {
2057 // If we've prompted, we need to hear from the user before we
2059 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2060 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2062 int num_downloads_blocking
;
2063 Browser::DownloadClosePreventionType dialog_type
=
2064 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2065 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2068 // Closing this window will kill some downloads; prompt to make sure
2070 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2071 window_
->ConfirmBrowserCloseWithPendingDownloads(
2072 num_downloads_blocking
,
2075 base::Bind(&Browser::InProgressDownloadResponse
,
2076 weak_factory_
.GetWeakPtr()));
2078 // Return false so the browser does not close. We'll close if the user
2079 // confirms in the dialog.
2083 ///////////////////////////////////////////////////////////////////////////////
2084 // Browser, Assorted utility functions (private):
2086 void Browser::SetAsDelegate(WebContents
* web_contents
, Browser
* delegate
) {
2088 web_contents
->SetDelegate(delegate
);
2090 // ...and all the helpers.
2091 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2092 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2093 SetDelegate(delegate
);
2094 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2095 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2096 ZoomController::FromWebContents(web_contents
)->set_observer(delegate
);
2097 TranslateTabHelper
* translate_tab_helper
=
2098 TranslateTabHelper::FromWebContents(web_contents
);
2099 translate_tab_helper
->language_state().set_observer(
2100 delegate
? delegate
->language_state_observer_
.get() : NULL
);
2103 void Browser::CloseFrame() {
2107 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2110 if (type
== DETACH_TYPE_DETACH
) {
2111 // Save the current location bar state, but only if the tab being detached
2112 // is the selected tab. Because saving state can conditionally revert the
2113 // location bar, saving the current tab's location bar state to a
2114 // non-selected tab can corrupt both tabs.
2115 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2116 LocationBar
* location_bar
= window()->GetLocationBar();
2118 location_bar
->SaveStateToContents(contents
);
2121 if (!tab_strip_model_
->closing_all())
2122 SyncHistoryWithTabs(0);
2125 SetAsDelegate(contents
, NULL
);
2126 RemoveScheduledUpdatesFor(contents
);
2128 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2129 find_bar_controller_
->ChangeWebContents(NULL
);
2132 // Stop observing search model changes for this tab.
2133 search_delegate_
->OnTabDetached(contents
);
2135 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2136 if (interstitial_observers_
[i
]->web_contents() != contents
)
2139 delete interstitial_observers_
[i
];
2140 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2145 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2146 bool check_fullscreen
) const {
2147 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2149 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2151 if (is_type_tabbed())
2152 features
|= FEATURE_BOOKMARKBAR
;
2154 if (!hide_ui_for_fullscreen
) {
2155 if (!is_type_tabbed())
2156 features
|= FEATURE_TITLEBAR
;
2158 if (is_type_tabbed())
2159 features
|= FEATURE_TABSTRIP
;
2161 if (is_type_tabbed())
2162 features
|= FEATURE_TOOLBAR
;
2164 if (!is_app() || ((app_type() == APP_TYPE_HOST
||
2165 app_name() == DevToolsWindow::kDevToolsApp
) &&
2166 CommandLine::ForCurrentProcess()->HasSwitch(
2167 switches::kEnableStreamlinedHostedApps
))) {
2168 features
|= FEATURE_LOCATIONBAR
;
2171 return !!(features
& feature
);
2174 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2175 BookmarkBar::State state
;
2176 // The bookmark bar is hidden in fullscreen mode, unless on the new tab page.
2177 if (browser_defaults::bookmarks_enabled
&&
2178 profile_
->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar
) &&
2179 !ShouldHideUIForFullscreen()) {
2180 state
= BookmarkBar::SHOW
;
2182 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2183 BookmarkTabHelper
* bookmark_tab_helper
=
2184 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2185 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2186 state
= BookmarkBar::DETACHED
;
2188 state
= BookmarkBar::HIDDEN
;
2191 if (state
== bookmark_bar_state_
)
2194 bookmark_bar_state_
= state
;
2197 return; // This is called from the constructor when window_ is NULL.
2199 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2200 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2201 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2202 // end up querying state once they process the tab switch.
2206 bool shouldAnimate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2207 window_
->BookmarkBarStateChanged(shouldAnimate
?
2208 BookmarkBar::ANIMATE_STATE_CHANGE
:
2209 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2212 bool Browser::ShouldHideUIForFullscreen() const {
2213 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2214 // keep the controls in a slide-down panel.
2215 return window_
&& window_
->ShouldHideUIForFullscreen();
2218 bool Browser::MaybeCreateBackgroundContents(
2220 WebContents
* opener_web_contents
,
2221 const base::string16
& frame_name
,
2222 const GURL
& target_url
,
2223 const std::string
& partition_id
,
2224 content::SessionStorageNamespace
* session_storage_namespace
) {
2225 GURL opener_url
= opener_web_contents
->GetURL();
2226 ExtensionService
* extensions_service
=
2227 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2229 if (!opener_url
.is_valid() ||
2230 frame_name
.empty() ||
2231 !extensions_service
||
2232 !extensions_service
->is_ready())
2235 // Only hosted apps have web extents, so this ensures that only hosted apps
2236 // can create BackgroundContents. We don't have to check for background
2237 // permission as that is checked in RenderMessageFilter when the CreateWindow
2238 // message is processed.
2239 const Extension
* extension
=
2240 extensions_service
->extensions()->GetHostedAppByURL(opener_url
);
2244 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2245 BackgroundContentsService
* service
=
2246 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2250 // Ensure that we're trying to open this from the extension's process.
2251 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2252 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2253 if (!opener_site_instance
->GetProcess() ||
2254 !process_map
->Contains(
2255 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2259 // Only allow a single background contents per app.
2260 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2261 BackgroundContents
* existing
=
2262 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2264 // For non-scriptable background contents, ignore the request altogether,
2265 // (returning true, so that a regular WebContents isn't created either).
2266 if (!allow_js_access
)
2268 // For scriptable background pages, if one already exists, close it (even
2269 // if it was specified in the manifest).
2273 // If script access is not allowed, create the the background contents in a
2274 // new SiteInstance, so that a separate process is used.
2275 scoped_refptr
<content::SiteInstance
> site_instance
=
2277 opener_site_instance
:
2278 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2280 // Passed all the checks, so this should be created as a BackgroundContents.
2281 BackgroundContents
* contents
=
2282 service
->CreateBackgroundContents(site_instance
.get(),
2286 base::ASCIIToUTF16(extension
->id()),
2288 session_storage_namespace
);
2290 // When a separate process is used, the original renderer cannot access the
2291 // new window later, thus we need to navigate the window now.
2292 if (contents
&& !allow_js_access
) {
2293 contents
->web_contents()->GetController().LoadURL(
2295 content::Referrer(),
2296 content::PAGE_TRANSITION_LINK
,
2297 std::string()); // No extra headers.
2300 return contents
!= NULL
;