Infobar material design refresh: layout
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob5ad781c63e1c0d52ad5d5abeda232e7c3ee7c987
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"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #endif // defined(OS_WIN)
12 #include <algorithm>
13 #include <string>
15 #include "base/base_paths.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/metrics/histogram.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/process_info.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/thread_task_runner_handle.h"
30 #include "base/threading/thread.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/time/time.h"
33 #include "chrome/app/chrome_command_ids.h"
34 #include "chrome/browser/app_mode/app_mode_utils.h"
35 #include "chrome/browser/autofill/personal_data_manager_factory.h"
36 #include "chrome/browser/background/background_contents.h"
37 #include "chrome/browser/background/background_contents_service.h"
38 #include "chrome/browser/background/background_contents_service_factory.h"
39 #include "chrome/browser/browser_process.h"
40 #include "chrome/browser/browser_shutdown.h"
41 #include "chrome/browser/character_encoding.h"
42 #include "chrome/browser/chrome_notification_types.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/custom_handlers/register_protocol_handler_permission_request.h"
48 #include "chrome/browser/defaults.h"
49 #include "chrome/browser/devtools/devtools_toggle_action.h"
50 #include "chrome/browser/devtools/devtools_window.h"
51 #include "chrome/browser/download/download_service.h"
52 #include "chrome/browser/download/download_service_factory.h"
53 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
55 #include "chrome/browser/extensions/browser_extension_window_controller.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_ui_util.h"
58 #include "chrome/browser/extensions/extension_util.h"
59 #include "chrome/browser/extensions/tab_helper.h"
60 #include "chrome/browser/file_select_helper.h"
61 #include "chrome/browser/first_run/first_run.h"
62 #include "chrome/browser/history/top_sites_factory.h"
63 #include "chrome/browser/infobars/infobar_service.h"
64 #include "chrome/browser/lifetime/application_lifetime.h"
65 #include "chrome/browser/notifications/notification_ui_manager.h"
66 #include "chrome/browser/pepper_broker_infobar_delegate.h"
67 #include "chrome/browser/prefs/incognito_mode_prefs.h"
68 #include "chrome/browser/profiles/profile.h"
69 #include "chrome/browser/profiles/profile_destroyer.h"
70 #include "chrome/browser/profiles/profile_metrics.h"
71 #include "chrome/browser/profiles/profiles_state.h"
72 #include "chrome/browser/repost_form_warning_controller.h"
73 #include "chrome/browser/search/search.h"
74 #include "chrome/browser/sessions/session_restore.h"
75 #include "chrome/browser/sessions/session_service.h"
76 #include "chrome/browser/sessions/session_service_factory.h"
77 #include "chrome/browser/sessions/session_tab_helper.h"
78 #include "chrome/browser/sessions/tab_restore_service.h"
79 #include "chrome/browser/sessions/tab_restore_service_factory.h"
80 #include "chrome/browser/sync/profile_sync_service.h"
81 #include "chrome/browser/sync/profile_sync_service_factory.h"
82 #include "chrome/browser/sync/sync_ui_util.h"
83 #include "chrome/browser/tab_contents/retargeting_details.h"
84 #include "chrome/browser/tab_contents/tab_util.h"
85 #include "chrome/browser/task_management/web_contents_tags.h"
86 #include "chrome/browser/themes/theme_service.h"
87 #include "chrome/browser/themes/theme_service_factory.h"
88 #include "chrome/browser/translate/chrome_translate_client.h"
89 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
90 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
91 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
92 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
93 #include "chrome/browser/ui/browser_command_controller.h"
94 #include "chrome/browser/ui/browser_commands.h"
95 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
96 #include "chrome/browser/ui/browser_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/exclusive_access/fullscreen_controller.h"
111 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
112 #include "chrome/browser/ui/extensions/hosted_app_browser_controller.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/global_error/global_error.h"
118 #include "chrome/browser/ui/global_error/global_error_service.h"
119 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
120 #include "chrome/browser/ui/location_bar/location_bar.h"
121 #include "chrome/browser/ui/media_utils.h"
122 #include "chrome/browser/ui/search/search_delegate.h"
123 #include "chrome/browser/ui/search/search_model.h"
124 #include "chrome/browser/ui/search/search_tab_helper.h"
125 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
126 #include "chrome/browser/ui/settings_window_manager.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_dialogs.h"
132 #include "chrome/browser/ui/tab_helpers.h"
133 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
134 #include "chrome/browser/ui/tabs/tab_menu_model.h"
135 #include "chrome/browser/ui/tabs/tab_strip_model.h"
136 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
137 #include "chrome/browser/ui/tabs/tab_utils.h"
138 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
139 #include "chrome/browser/ui/unload_controller.h"
140 #include "chrome/browser/ui/validation_message_bubble.h"
141 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
142 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
143 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
144 #include "chrome/browser/ui/window_sizer/window_sizer.h"
145 #include "chrome/browser/upgrade_detector.h"
146 #include "chrome/common/chrome_constants.h"
147 #include "chrome/common/chrome_switches.h"
148 #include "chrome/common/custom_handlers/protocol_handler.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 "chrome/grit/chromium_strings.h"
154 #include "chrome/grit/generated_resources.h"
155 #include "chrome/grit/locale_settings.h"
156 #include "components/app_modal/javascript_dialog_manager.h"
157 #include "components/bookmarks/browser/bookmark_model.h"
158 #include "components/bookmarks/browser/bookmark_utils.h"
159 #include "components/content_settings/core/browser/host_content_settings_map.h"
160 #include "components/favicon/content/content_favicon_driver.h"
161 #include "components/history/core/browser/top_sites.h"
162 #include "components/search/search.h"
163 #include "components/sessions/session_types.h"
164 #include "components/startup_metric_utils/startup_metric_utils.h"
165 #include "components/translate/core/browser/language_state.h"
166 #include "components/ui/zoom/zoom_controller.h"
167 #include "components/web_modal/web_contents_modal_dialog_manager.h"
168 #include "content/public/browser/devtools_agent_host.h"
169 #include "content/public/browser/interstitial_page.h"
170 #include "content/public/browser/invalidate_type.h"
171 #include "content/public/browser/navigation_controller.h"
172 #include "content/public/browser/navigation_entry.h"
173 #include "content/public/browser/notification_details.h"
174 #include "content/public/browser/notification_service.h"
175 #include "content/public/browser/plugin_service.h"
176 #include "content/public/browser/render_process_host.h"
177 #include "content/public/browser/render_view_host.h"
178 #include "content/public/browser/render_widget_host_view.h"
179 #include "content/public/browser/security_style_explanation.h"
180 #include "content/public/browser/security_style_explanations.h"
181 #include "content/public/browser/site_instance.h"
182 #include "content/public/browser/user_metrics.h"
183 #include "content/public/browser/web_contents.h"
184 #include "content/public/common/content_switches.h"
185 #include "content/public/common/page_zoom.h"
186 #include "content/public/common/renderer_preferences.h"
187 #include "content/public/common/ssl_status.h"
188 #include "content/public/common/webplugininfo.h"
189 #include "extensions/browser/extension_prefs.h"
190 #include "extensions/browser/extension_registry.h"
191 #include "extensions/browser/extension_system.h"
192 #include "extensions/common/constants.h"
193 #include "extensions/common/extension.h"
194 #include "extensions/common/manifest_handlers/background_info.h"
195 #include "net/base/filename_util.h"
196 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
197 #include "net/cookies/cookie_monster.h"
198 #include "net/url_request/url_request_context.h"
199 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
200 #include "ui/base/l10n/l10n_util.h"
201 #include "ui/base/window_open_disposition.h"
202 #include "ui/gfx/geometry/point.h"
203 #include "ui/shell_dialogs/selected_file_info.h"
205 #if defined(OS_WIN)
206 #include "base/win/metro.h"
207 #include "chrome/browser/ssl/ssl_error_info.h"
208 #include "chrome/browser/task_manager/task_manager.h"
209 #include "chrome/browser/ui/view_ids.h"
210 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
211 #include "components/browser_watcher/exit_funnel_win.h"
212 #include "ui/base/touch/touch_device.h"
213 #include "ui/base/win/shell.h"
214 #endif // OS_WIN
216 #if defined(OS_CHROMEOS)
217 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
218 #endif
220 #if defined(USE_ASH)
221 #include "ash/ash_switches.h"
222 #endif
224 using base::TimeDelta;
225 using base::UserMetricsAction;
226 using content::NativeWebKeyboardEvent;
227 using content::NavigationController;
228 using content::NavigationEntry;
229 using content::OpenURLParams;
230 using content::PluginService;
231 using content::Referrer;
232 using content::RenderWidgetHostView;
233 using content::SiteInstance;
234 using content::WebContents;
235 using extensions::Extension;
236 using ui::WebDialogDelegate;
237 using web_modal::WebContentsModalDialogManager;
238 using blink::WebWindowFeatures;
240 ///////////////////////////////////////////////////////////////////////////////
242 namespace {
244 // How long we wait before updating the browser chrome while loading a page.
245 const int kUIUpdateCoalescingTimeMS = 200;
247 BrowserWindow* CreateBrowserWindow(Browser* browser) {
248 return BrowserWindow::CreateBrowserWindow(browser);
251 // Is the fast tab unload experiment enabled?
252 bool IsFastTabUnloadEnabled() {
253 return base::CommandLine::ForCurrentProcess()->HasSwitch(
254 switches::kEnableFastUnload);
257 } // namespace
259 ////////////////////////////////////////////////////////////////////////////////
260 // Browser, CreateParams:
262 Browser::CreateParams::CreateParams(Profile* profile,
263 chrome::HostDesktopType host_desktop_type)
264 : type(TYPE_TABBED),
265 profile(profile),
266 host_desktop_type(host_desktop_type),
267 trusted_source(false),
268 initial_show_state(ui::SHOW_STATE_DEFAULT),
269 is_session_restore(false),
270 window(NULL) {
273 Browser::CreateParams::CreateParams(Type type,
274 Profile* profile,
275 chrome::HostDesktopType host_desktop_type)
276 : type(type),
277 profile(profile),
278 host_desktop_type(host_desktop_type),
279 trusted_source(false),
280 initial_show_state(ui::SHOW_STATE_DEFAULT),
281 is_session_restore(false),
282 window(NULL) {
285 // static
286 Browser::CreateParams Browser::CreateParams::CreateForApp(
287 const std::string& app_name,
288 bool trusted_source,
289 const gfx::Rect& window_bounds,
290 Profile* profile,
291 chrome::HostDesktopType host_desktop_type) {
292 DCHECK(!app_name.empty());
294 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
295 params.app_name = app_name;
296 params.trusted_source = trusted_source;
297 params.initial_bounds = window_bounds;
299 return params;
302 // static
303 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
304 Profile* profile,
305 chrome::HostDesktopType host_desktop_type) {
306 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
307 params.app_name = DevToolsWindow::kDevToolsApp;
308 params.trusted_source = true;
309 return params;
312 ////////////////////////////////////////////////////////////////////////////////
313 // Browser, InterstitialObserver:
315 class Browser::InterstitialObserver : public content::WebContentsObserver {
316 public:
317 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
318 : WebContentsObserver(web_contents),
319 browser_(browser) {
322 void DidAttachInterstitialPage() override {
323 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
326 void DidDetachInterstitialPage() override {
327 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
330 private:
331 Browser* browser_;
333 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
336 ///////////////////////////////////////////////////////////////////////////////
337 // Browser, Constructors, Creation, Showing:
339 Browser::Browser(const CreateParams& params)
340 : extension_registry_observer_(this),
341 type_(params.type),
342 profile_(params.profile),
343 window_(NULL),
344 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
345 tab_strip_model_(
346 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
347 app_name_(params.app_name),
348 is_trusted_source_(params.trusted_source),
349 cancel_download_confirmation_state_(NOT_PROMPTED),
350 override_bounds_(params.initial_bounds),
351 initial_show_state_(params.initial_show_state),
352 is_session_restore_(params.is_session_restore),
353 host_desktop_type_(
354 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
355 content_setting_bubble_model_delegate_(
356 new BrowserContentSettingBubbleModelDelegate(this)),
357 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
358 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
359 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
360 bookmark_bar_state_(BookmarkBar::HIDDEN),
361 command_controller_(new chrome::BrowserCommandController(this)),
362 window_has_shown_(false),
363 chrome_updater_factory_(this),
364 weak_factory_(this) {
365 // If this causes a crash then a window is being opened using a profile type
366 // that is disallowed by policy. The crash prevents the disabled window type
367 // from opening at all, but the path that triggered it should be fixed.
368 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
369 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
370 << "Only off the record browser may be opened in guest mode";
371 DCHECK(!profile_->IsSystemProfile())
372 << "The system profile should never have a real browser.";
373 // TODO(mlerman): After this hits stable channel, see if there are counts
374 // for this metric. If not, change the DCHECK above to a CHECK.
375 if (profile_->IsSystemProfile())
376 content::RecordAction(base::UserMetricsAction("BrowserForSystemProfile"));
378 // TODO(jeremy): Move to initializer list once flag is removed.
379 if (IsFastTabUnloadEnabled())
380 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
381 else
382 unload_controller_.reset(new chrome::UnloadController(this));
384 tab_strip_model_->AddObserver(this);
386 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
387 search_model_.reset(new SearchModel());
388 search_delegate_.reset(new SearchDelegate(search_model_.get()));
390 extension_registry_observer_.Add(
391 extensions::ExtensionRegistry::Get(profile_));
392 registrar_.Add(this,
393 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
394 content::NotificationService::AllSources());
395 #if defined(ENABLE_THEMES)
396 registrar_.Add(
397 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
398 content::Source<ThemeService>(
399 ThemeServiceFactory::GetForProfile(profile_)));
400 #endif
401 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
402 content::NotificationService::AllSources());
404 profile_pref_registrar_.Init(profile_->GetPrefs());
405 profile_pref_registrar_.Add(
406 prefs::kDevToolsDisabled,
407 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
408 profile_pref_registrar_.Add(
409 bookmarks::prefs::kShowBookmarkBar,
410 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
411 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
413 // NOTE: These prefs all need to be explicitly destroyed in the destructor
414 // or you'll get a nasty surprise when you run the incognito tests.
415 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
416 profile_->GetPrefs());
418 if (search::IsInstantExtendedAPIEnabled() && is_type_tabbed())
419 instant_controller_.reset(new BrowserInstantController(this));
421 if (extensions::HostedAppBrowserController::IsForHostedApp(this)) {
422 hosted_app_controller_.reset(
423 new extensions::HostedAppBrowserController(this));
426 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
428 ProfileMetrics::LogProfileLaunch(profile_);
430 window_ = params.window ? params.window : CreateBrowserWindow(this);
432 if (hosted_app_controller_)
433 hosted_app_controller_->UpdateLocationBarVisibility(false);
435 // Create the extension window controller before sending notifications.
436 extension_window_controller_.reset(
437 new BrowserExtensionWindowController(this));
439 SessionService* session_service =
440 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
441 if (session_service)
442 session_service->WindowOpened(this);
444 // TODO(beng): move to ChromeBrowserMain:
445 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
446 #if defined(OS_WIN)
447 // Notify PDM that this is a first run.
448 ImportAutofillDataWin(
449 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
450 #endif // defined(OS_WIN)
453 exclusive_access_manager_.reset(
454 new ExclusiveAccessManager(window_->GetExclusiveAccessContext()));
456 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
457 // replace uses of this with BL's notifications.
458 BrowserList::AddBrowser(this);
459 content::NotificationService::current()->Notify(
460 chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::Source<Browser>(this),
461 content::NotificationService::NoDetails());
464 Browser::~Browser() {
465 // Stop observing notifications before continuing with destruction. Profile
466 // destruction will unload extensions and reentrant calls to Browser:: should
467 // be avoided while it is being torn down.
468 registrar_.RemoveAll();
469 extension_registry_observer_.RemoveAll();
471 // The tab strip should not have any tabs at this point.
472 DCHECK(tab_strip_model_->empty());
473 tab_strip_model_->RemoveObserver(this);
474 bubble_manager_.reset();
476 // Destroy the BrowserCommandController before removing the browser, so that
477 // it doesn't act on any notifications that are sent as a result of removing
478 // the browser.
479 command_controller_.reset();
480 BrowserList::RemoveBrowser(this);
482 SessionService* session_service =
483 SessionServiceFactory::GetForProfile(profile_);
484 if (session_service)
485 session_service->WindowClosed(session_id_);
487 TabRestoreService* tab_restore_service =
488 TabRestoreServiceFactory::GetForProfile(profile());
489 if (tab_restore_service)
490 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
492 #if !defined(OS_MACOSX)
493 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
494 // We're the last browser window with this profile. We need to nuke the
495 // TabRestoreService, which will start the shutdown of the
496 // NavigationControllers and allow for proper shutdown. If we don't do this
497 // chrome won't shutdown cleanly, and may end up crashing when some
498 // thread tries to use the IO thread (or another thread) that is no longer
499 // valid.
500 // This isn't a valid assumption for Mac OS, as it stays running after
501 // the last browser has closed. The Mac equivalent is in its app
502 // controller.
503 TabRestoreServiceFactory::ResetForProfile(profile_);
505 #endif
507 profile_pref_registrar_.RemoveAll();
509 encoding_auto_detect_.Destroy();
511 // Destroy BrowserExtensionWindowController before the incognito profile
512 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
513 extension_window_controller_.reset();
515 // Destroy BrowserInstantController before the incongnito profile is destroyed
516 // because the InstantController destructor depends on this profile.
517 instant_controller_.reset();
519 if (profile_->IsOffTheRecord() &&
520 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
521 if (profile_->IsGuestSession()) {
522 // ChromeOS handles guest data independently.
523 #if !defined(OS_CHROMEOS)
524 // Clear all browsing data once a Guest Session completes. The Guest
525 // profile has BrowserContextKeyedServices that the Incognito profile
526 // doesn't, so the ProfileDestroyer can't delete it properly.
527 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
528 profiles::RemoveBrowsingDataForProfile(profile_->GetPath());
529 #endif
530 } else {
531 // An incognito profile is no longer needed, this indirectly frees
532 // its cache and cookies once it gets destroyed at the appropriate time.
533 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
537 // There may be pending file dialogs, we need to tell them that we've gone
538 // away so they don't try and call back to us.
539 if (select_file_dialog_.get())
540 select_file_dialog_->ListenerDestroyed();
542 int num_downloads;
543 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
544 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
545 !browser_defaults::kBrowserAliveWithNoWindows) {
546 DownloadService::CancelAllDownloads();
550 ///////////////////////////////////////////////////////////////////////////////
551 // Getters & Setters
553 ChromeBubbleManager* Browser::GetBubbleManager() {
554 if (!bubble_manager_)
555 bubble_manager_.reset(new ChromeBubbleManager(tab_strip_model_.get()));
556 return bubble_manager_.get();
559 FindBarController* Browser::GetFindBarController() {
560 if (!find_bar_controller_.get()) {
561 FindBar* find_bar = window_->CreateFindBar();
562 find_bar_controller_.reset(new FindBarController(find_bar));
563 find_bar->SetFindBarController(find_bar_controller_.get());
564 find_bar_controller_->ChangeWebContents(
565 tab_strip_model_->GetActiveWebContents());
566 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
568 return find_bar_controller_.get();
571 bool Browser::HasFindBarController() const {
572 return find_bar_controller_.get() != NULL;
575 bool Browser::is_app() const {
576 return !app_name_.empty();
579 bool Browser::is_devtools() const {
580 return app_name_ == DevToolsWindow::kDevToolsApp;
583 ///////////////////////////////////////////////////////////////////////////////
584 // Browser, State Storage and Retrieval for UI:
586 gfx::Image Browser::GetCurrentPageIcon() const {
587 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
588 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
589 // window during the window's creation (before tabs have been added).
590 favicon::FaviconDriver* favicon_driver =
591 web_contents
592 ? favicon::ContentFaviconDriver::FromWebContents(web_contents)
593 : nullptr;
594 return favicon_driver ? favicon_driver->GetFavicon() : gfx::Image();
597 base::string16 Browser::GetWindowTitleForCurrentTab() const {
598 WebContents* contents = tab_strip_model_->GetActiveWebContents();
599 base::string16 title;
601 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
602 // window during the window's creation (before tabs have been added).
603 if (contents) {
604 // The web app frame uses the host instead of the title.
605 if (ShouldUseWebAppFrame())
606 return base::UTF8ToUTF16(contents->GetURL().host());
608 title = contents->GetTitle();
609 FormatTitleForDisplay(&title);
611 if (title.empty())
612 title = CoreTabHelper::GetDefaultTitle();
614 #if defined(OS_MACOSX)
615 // On Mac, we don't want to suffix the page title with
616 // the application name.
617 return title;
618 #elif defined(USE_ASH)
619 // On Ash, we don't want to suffix the page title with the application name,
620 // but on Windows, where USE_ASH can also be true, we still want the prefix
621 // on desktop.
622 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
623 return title;
624 #endif
625 // Don't append the app name to window titles on app frames and app popups
626 return is_app() ?
627 title :
628 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
631 // static
632 void Browser::FormatTitleForDisplay(base::string16* title) {
633 size_t current_index = 0;
634 size_t match_index;
635 while ((match_index = title->find(L'\n', current_index)) !=
636 base::string16::npos) {
637 title->replace(match_index, 1, base::string16());
638 current_index = match_index;
642 ///////////////////////////////////////////////////////////////////////////////
643 // Browser, OnBeforeUnload handling:
645 bool Browser::ShouldCloseWindow() {
646 if (!CanCloseWithInProgressDownloads())
647 return false;
649 if (IsFastTabUnloadEnabled())
650 return fast_unload_controller_->ShouldCloseWindow();
651 return unload_controller_->ShouldCloseWindow();
654 bool Browser::CallBeforeUnloadHandlers(
655 const base::Callback<void(bool)>& on_close_confirmed) {
656 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
657 if (IsFastTabUnloadEnabled()) {
658 return fast_unload_controller_->CallBeforeUnloadHandlers(
659 on_close_confirmed);
661 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
664 void Browser::ResetBeforeUnloadHandlers() {
665 cancel_download_confirmation_state_ = NOT_PROMPTED;
666 if (IsFastTabUnloadEnabled())
667 fast_unload_controller_->ResetBeforeUnloadHandlers();
668 else
669 unload_controller_->ResetBeforeUnloadHandlers();
672 bool Browser::HasCompletedUnloadProcessing() const {
673 DCHECK(IsFastTabUnloadEnabled());
674 return fast_unload_controller_->HasCompletedUnloadProcessing();
677 bool Browser::IsAttemptingToCloseBrowser() const {
678 if (IsFastTabUnloadEnabled())
679 return fast_unload_controller_->is_attempting_to_close_browser();
680 return unload_controller_->is_attempting_to_close_browser();
683 void Browser::OnWindowClosing() {
684 if (!ShouldCloseWindow())
685 return;
687 // Application should shutdown on last window close if the user is explicitly
688 // trying to quit, or if there is nothing keeping the browser alive (such as
689 // AppController on the Mac, or BackgroundContentsService for background
690 // pages).
691 bool should_quit_if_last_browser =
692 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
694 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this)) {
695 #if defined(OS_WIN)
696 browser_watcher::ExitFunnel::RecordSingleEvent(
697 chrome::kBrowserExitCodesRegistryPath, L"LastWindowClose");
698 #endif
699 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
702 // Don't use GetForProfileIfExisting here, we want to force creation of the
703 // session service so that user can restore what was open.
704 SessionService* session_service =
705 SessionServiceFactory::GetForProfile(profile());
706 if (session_service)
707 session_service->WindowClosing(session_id());
709 TabRestoreService* tab_restore_service =
710 TabRestoreServiceFactory::GetForProfile(profile());
712 #if defined(USE_AURA)
713 if (tab_restore_service && is_app() && !is_devtools())
714 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
715 #endif
717 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
718 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
720 // TODO(sky): convert session/tab restore to use notification.
721 content::NotificationService::current()->Notify(
722 chrome::NOTIFICATION_BROWSER_CLOSING,
723 content::Source<Browser>(this),
724 content::NotificationService::NoDetails());
726 if (!IsFastTabUnloadEnabled())
727 tab_strip_model_->CloseAllTabs();
730 ////////////////////////////////////////////////////////////////////////////////
731 // In-progress download termination handling:
733 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
734 if (cancel_downloads) {
735 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
736 chrome::CloseWindow(this);
737 return;
740 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
741 // close again we'll show the warning again.
742 cancel_download_confirmation_state_ = NOT_PROMPTED;
744 // Show the download page so the user can figure-out what downloads are still
745 // in-progress.
746 chrome::ShowDownloads(this);
748 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
749 // prompt every time any tab is closed. http://crbug.com/305516
750 if (IsFastTabUnloadEnabled())
751 fast_unload_controller_->CancelWindowClose();
752 else
753 unload_controller_->CancelWindowClose();
756 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
757 int* num_downloads_blocking) const {
758 DCHECK(num_downloads_blocking);
759 *num_downloads_blocking = 0;
761 // If we're not running a full browser process with a profile manager
762 // (testing), it's ok to close the browser.
763 if (!g_browser_process->profile_manager())
764 return DOWNLOAD_CLOSE_OK;
766 int total_download_count =
767 DownloadService::NonMaliciousDownloadCountAllProfiles();
768 if (total_download_count == 0)
769 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
771 // Figure out how many windows are open total, and associated with this
772 // profile, that are relevant for the ok-to-close decision.
773 int profile_window_count = 0;
774 int total_window_count = 0;
775 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
776 // Don't count this browser window or any other in the process of closing.
777 Browser* const browser = *it;
778 // Window closing may be delayed, and windows that are in the process of
779 // closing don't count against our totals.
780 if (browser == this || browser->IsAttemptingToCloseBrowser())
781 continue;
783 if (it->profile() == profile())
784 profile_window_count++;
785 total_window_count++;
788 // If there aren't any other windows, we're at browser shutdown,
789 // which would cancel all current downloads.
790 if (total_window_count == 0) {
791 *num_downloads_blocking = total_download_count;
792 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
795 // If there aren't any other windows on our profile, and we're an incognito
796 // profile, and there are downloads associated with that profile,
797 // those downloads would be cancelled by our window (-> profile) close.
798 DownloadService* download_service =
799 DownloadServiceFactory::GetForBrowserContext(profile());
800 if ((profile_window_count == 0) &&
801 (download_service->NonMaliciousDownloadCount() > 0) &&
802 profile()->IsOffTheRecord()) {
803 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
804 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
807 // Those are the only conditions under which we will block shutdown.
808 return DOWNLOAD_CLOSE_OK;
811 ////////////////////////////////////////////////////////////////////////////////
812 // Browser, Tab adding/showing functions:
814 void Browser::WindowFullscreenStateChanged() {
815 exclusive_access_manager_->fullscreen_controller()
816 ->WindowFullscreenStateChanged();
817 command_controller_->FullscreenStateChanged();
818 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
821 ///////////////////////////////////////////////////////////////////////////////
822 // Browser, Assorted browser commands:
824 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
825 exclusive_access_manager_->fullscreen_controller()
826 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
829 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
830 return SupportsWindowFeatureImpl(feature, true);
833 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
834 return SupportsWindowFeatureImpl(feature, false);
837 void Browser::ToggleEncodingAutoDetect() {
838 content::RecordAction(UserMetricsAction("AutoDetectChange"));
839 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
840 // If "auto detect" is turned on, then any current override encoding
841 // is cleared. This also implicitly performs a reload.
842 // OTOH, if "auto detect" is turned off, we don't change the currently
843 // active encoding.
844 if (encoding_auto_detect_.GetValue()) {
845 WebContents* contents = tab_strip_model_->GetActiveWebContents();
846 if (contents)
847 contents->ResetOverrideEncoding();
851 void Browser::OverrideEncoding(int encoding_id) {
852 content::RecordAction(UserMetricsAction("OverrideEncoding"));
853 const std::string selected_encoding =
854 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
855 WebContents* contents = tab_strip_model_->GetActiveWebContents();
856 if (!selected_encoding.empty() && contents)
857 contents->SetOverrideEncoding(selected_encoding);
858 // Update the list of recently selected encodings.
859 std::string new_selected_encoding_list;
860 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
861 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
862 encoding_id,
863 &new_selected_encoding_list)) {
864 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
865 new_selected_encoding_list);
869 void Browser::OpenFile() {
870 content::RecordAction(UserMetricsAction("OpenFile"));
871 select_file_dialog_ = ui::SelectFileDialog::Create(
872 this, new ChromeSelectFilePolicy(
873 tab_strip_model_->GetActiveWebContents()));
875 const base::FilePath directory = profile_->last_selected_directory();
877 // TODO(beng): figure out how to juggle this.
878 gfx::NativeWindow parent_window = window_->GetNativeWindow();
879 ui::SelectFileDialog::FileTypeInfo file_types;
880 file_types.support_drive = true;
881 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
882 base::string16(),
883 directory,
884 &file_types,
886 base::FilePath::StringType(),
887 parent_window,
888 NULL);
891 void Browser::UpdateDownloadShelfVisibility(bool visible) {
892 if (GetStatusBubble())
893 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
896 ///////////////////////////////////////////////////////////////////////////////
898 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
899 ui::PageTransition transition,
900 bool user_initiated) {
901 tab_strip_model_->TabNavigating(contents, transition);
903 bool contents_is_selected =
904 contents == tab_strip_model_->GetActiveWebContents();
905 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
906 // Forcibly reset the location bar if the url is going to change in the
907 // current tab, since otherwise it won't discard any ongoing user edits,
908 // since it doesn't realize this is a user-initiated action.
909 window()->GetLocationBar()->Revert();
912 if (GetStatusBubble())
913 GetStatusBubble()->Hide();
915 // Update the location bar. This is synchronous. We specifically don't
916 // update the load state since the load hasn't started yet and updating it
917 // will put it out of sync with the actual state like whether we're
918 // displaying a favicon, which controls the throbber. If we updated it here,
919 // the throbber will show the default favicon for a split second when
920 // navigating away from the new tab page.
921 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
923 if (contents_is_selected)
924 contents->SetInitialFocus();
927 ///////////////////////////////////////////////////////////////////////////////
928 // Browser, PageNavigator implementation:
930 WebContents* Browser::OpenURL(const OpenURLParams& params) {
931 return OpenURLFromTab(NULL, params);
934 ///////////////////////////////////////////////////////////////////////////////
935 // Browser, TabStripModelObserver implementation:
937 void Browser::TabInsertedAt(WebContents* contents,
938 int index,
939 bool foreground) {
940 SetAsDelegate(contents, true);
942 SessionTabHelper* session_tab_helper =
943 SessionTabHelper::FromWebContents(contents);
944 session_tab_helper->SetWindowID(session_id());
946 content::NotificationService::current()->Notify(
947 chrome::NOTIFICATION_TAB_PARENTED,
948 content::Source<content::WebContents>(contents),
949 content::NotificationService::NoDetails());
951 SyncHistoryWithTabs(index);
953 // Make sure the loading state is updated correctly, otherwise the throbber
954 // won't start if the page is loading.
955 LoadingStateChanged(contents, true);
957 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
959 SessionService* session_service =
960 SessionServiceFactory::GetForProfile(profile_);
961 if (session_service) {
962 session_service->TabInserted(contents);
963 int new_active_index = tab_strip_model_->active_index();
964 if (index < new_active_index)
965 session_service->SetSelectedTabInWindow(session_id(),
966 new_active_index);
970 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
971 WebContents* contents,
972 int index) {
973 exclusive_access_manager_->OnTabClosing(contents);
974 SessionService* session_service =
975 SessionServiceFactory::GetForProfile(profile_);
976 if (session_service)
977 session_service->TabClosing(contents);
978 content::NotificationService::current()->Notify(
979 chrome::NOTIFICATION_TAB_CLOSING,
980 content::Source<NavigationController>(&contents->GetController()),
981 content::NotificationService::NoDetails());
983 // Sever the WebContents' connection back to us.
984 SetAsDelegate(contents, false);
987 void Browser::TabDetachedAt(WebContents* contents, int index) {
988 // TabDetachedAt is called before TabStripModel has updated the
989 // active index.
990 int old_active_index = tab_strip_model_->active_index();
991 if (index < old_active_index && !tab_strip_model_->closing_all()) {
992 SessionService* session_service =
993 SessionServiceFactory::GetForProfileIfExisting(profile_);
994 if (session_service)
995 session_service->SetSelectedTabInWindow(session_id(),
996 old_active_index - 1);
999 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1002 void Browser::TabDeactivated(WebContents* contents) {
1003 exclusive_access_manager_->OnTabDeactivated(contents);
1004 search_delegate_->OnTabDeactivated(contents);
1005 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
1007 // Save what the user's currently typing, so it can be restored when we
1008 // switch back to this tab.
1009 window_->GetLocationBar()->SaveStateToContents(contents);
1011 if (instant_controller_)
1012 instant_controller_->TabDeactivated(contents);
1015 void Browser::ActiveTabChanged(WebContents* old_contents,
1016 WebContents* new_contents,
1017 int index,
1018 int reason) {
1019 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1021 // Update the bookmark state, since the BrowserWindow may query it during
1022 // OnActiveTabChanged() below.
1023 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1025 // Let the BrowserWindow do its handling. On e.g. views this changes the
1026 // focused object, which should happen before we update the toolbar below,
1027 // since the omnibox expects the correct element to already be focused when it
1028 // is updated.
1029 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1031 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
1033 // Discarded tabs always get reloaded.
1034 if (tab_strip_model_->IsTabDiscarded(index)) {
1035 LOG(WARNING) << "Reloading discarded tab at " << index;
1036 static int reload_count = 0;
1037 UMA_HISTOGRAM_CUSTOM_COUNTS(
1038 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1039 chrome::Reload(this, CURRENT_TAB);
1042 // If we have any update pending, do it now.
1043 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1044 ProcessPendingUIUpdates();
1046 // Propagate the profile to the location bar.
1047 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1049 if (search::IsInstantExtendedAPIEnabled())
1050 search_delegate_->OnTabActivated(new_contents);
1052 // Update reload/stop state.
1053 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1055 // Update commands to reflect current state.
1056 command_controller_->TabStateChanged();
1058 // Reset the status bubble.
1059 StatusBubble* status_bubble = GetStatusBubble();
1060 if (status_bubble) {
1061 status_bubble->Hide();
1063 // Show the loading state (if any).
1064 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1065 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1068 if (HasFindBarController()) {
1069 find_bar_controller_->ChangeWebContents(new_contents);
1070 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1073 // Update sessions (selected tab index and last active time). Don't force
1074 // creation of sessions. If sessions doesn't exist, the change will be picked
1075 // up by sessions when created.
1076 SessionService* session_service =
1077 SessionServiceFactory::GetForProfileIfExisting(profile_);
1078 if (session_service && !tab_strip_model_->closing_all()) {
1079 session_service->SetSelectedTabInWindow(session_id(),
1080 tab_strip_model_->active_index());
1081 if (SessionRestore::GetSmartRestoreMode() ==
1082 SessionRestore::SMART_RESTORE_MODE_MRU) {
1083 SessionTabHelper* session_tab_helper =
1084 SessionTabHelper::FromWebContents(new_contents);
1085 session_service->SetLastActiveTime(session_id(),
1086 session_tab_helper->session_id(),
1087 base::TimeTicks::Now());
1091 // This needs to be called after notifying SearchDelegate.
1092 if (instant_controller_)
1093 instant_controller_->ActiveTabChanged();
1095 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1096 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1099 void Browser::TabMoved(WebContents* contents,
1100 int from_index,
1101 int to_index) {
1102 DCHECK(from_index >= 0 && to_index >= 0);
1103 // Notify the history service.
1104 SyncHistoryWithTabs(std::min(from_index, to_index));
1107 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1108 WebContents* old_contents,
1109 WebContents* new_contents,
1110 int index) {
1111 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1112 exclusive_access_manager_->OnTabClosing(old_contents);
1113 SessionService* session_service =
1114 SessionServiceFactory::GetForProfile(profile_);
1115 if (session_service)
1116 session_service->TabClosing(old_contents);
1117 TabInsertedAt(new_contents,
1118 index,
1119 (index == tab_strip_model_->active_index()));
1121 int entry_count = new_contents->GetController().GetEntryCount();
1122 if (entry_count > 0) {
1123 // Send out notification so that observers are updated appropriately.
1124 new_contents->GetController().NotifyEntryChanged(
1125 new_contents->GetController().GetEntryAtIndex(entry_count - 1));
1128 if (session_service) {
1129 // The new_contents may end up with a different navigation stack. Force
1130 // the session service to update itself.
1131 session_service->TabRestored(new_contents,
1132 tab_strip_model_->IsTabPinned(index));
1136 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1137 SessionService* session_service =
1138 SessionServiceFactory::GetForProfileIfExisting(profile());
1139 if (session_service) {
1140 SessionTabHelper* session_tab_helper =
1141 SessionTabHelper::FromWebContents(contents);
1142 session_service->SetPinnedState(session_id(),
1143 session_tab_helper->session_id(),
1144 tab_strip_model_->IsTabPinned(index));
1148 void Browser::TabStripEmpty() {
1149 // Close the frame after we return to the message loop (not immediately,
1150 // otherwise it will destroy this object before the stack has a chance to
1151 // cleanly unwind.)
1152 // Note: This will be called several times if TabStripEmpty is called several
1153 // times. This is because it does not close the window if tabs are
1154 // still present.
1155 base::ThreadTaskRunnerHandle::Get()->PostTask(
1156 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1158 // Instant may have visible WebContents that need to be detached before the
1159 // window system closes.
1160 instant_controller_.reset();
1163 bool Browser::CanOverscrollContent() const {
1164 #if defined(OS_WIN)
1165 // Don't enable overscroll on Windows machines unless they have a touch
1166 // screen as these machines typically don't have a touchpad capable of
1167 // horizontal scrolling. We are purposefully biased towards "no" here,
1168 // so that we don't waste resources capturing screenshots for horizontal
1169 // overscroll navigation unnecessarily.
1170 bool allow_overscroll = ui::IsTouchDevicePresent();
1171 #elif defined(USE_AURA)
1172 bool allow_overscroll = true;
1173 #else
1174 bool allow_overscroll = false;
1175 #endif
1177 if (!allow_overscroll)
1178 return false;
1180 const std::string value =
1181 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1182 switches::kOverscrollHistoryNavigation);
1183 bool overscroll_enabled = value != "0";
1184 if (!overscroll_enabled)
1185 return false;
1186 if (is_app() || is_devtools() || !is_type_tabbed())
1187 return false;
1189 // The detached bookmark bar has appearance of floating above the
1190 // web-contents. This does not play nicely with overscroll navigation
1191 // gestures. So disable overscroll navigation when the bookmark bar is in the
1192 // detached state and the overscroll effect moves the layers.
1193 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1194 return false;
1195 return true;
1198 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1199 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1200 // other pages have committed.
1201 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1202 if (!profile || !source->GetController().GetLastCommittedEntry())
1203 return false;
1204 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1205 return search::IsNTPURL(committed_url, profile);
1208 void Browser::SetFocusToLocationBar(bool select_all) {
1209 // Two differences between this and FocusLocationBar():
1210 // (1) This doesn't get recorded in user metrics, since it's called
1211 // internally.
1212 // (2) This checks whether the location bar can be focused, and if not, clears
1213 // the focus. FocusLocationBar() is only reached when the location bar is
1214 // focusable, but this may be reached at other times, e.g. while in
1215 // fullscreen mode, where we need to leave focus in a consistent state.
1216 window_->SetFocusToLocationBar(select_all);
1219 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1220 const NativeWebKeyboardEvent& event,
1221 bool* is_keyboard_shortcut) {
1222 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1223 // TODO(koz): Write a test for this http://crbug.com/100441.
1224 if (event.windowsKeyCode == 27 &&
1225 exclusive_access_manager_->HandleUserPressedEscape()) {
1226 return true;
1228 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1231 void Browser::HandleKeyboardEvent(content::WebContents* source,
1232 const NativeWebKeyboardEvent& event) {
1233 DevToolsWindow* devtools_window =
1234 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1235 bool handled = false;
1236 if (devtools_window)
1237 handled = devtools_window->ForwardKeyboardEvent(event);
1239 if (!handled)
1240 window()->HandleKeyboardEvent(event);
1243 bool Browser::TabsNeedBeforeUnloadFired() {
1244 if (IsFastTabUnloadEnabled())
1245 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1246 return unload_controller_->TabsNeedBeforeUnloadFired();
1249 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1250 const gfx::Rect& anchor_in_root_view,
1251 const base::string16& main_text,
1252 const base::string16& sub_text) {
1253 validation_message_bubble_ =
1254 TabDialogs::FromWebContents(web_contents)
1255 ->ShowValidationMessage(anchor_in_root_view, main_text, sub_text);
1258 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1259 validation_message_bubble_.reset();
1262 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1263 const gfx::Rect& anchor_in_root_view) {
1264 if (!validation_message_bubble_)
1265 return;
1266 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1267 if (rwhv) {
1268 validation_message_bubble_->SetPositionRelativeToAnchor(
1269 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1273 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1274 const blink::WebGestureEvent& event) {
1275 // Disable pinch zooming in undocked dev tools window due to poor UX.
1276 if (app_name() == DevToolsWindow::kDevToolsApp)
1277 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1278 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1279 event.type == blink::WebGestureEvent::GesturePinchEnd;
1281 return false;
1284 bool Browser::CanDragEnter(content::WebContents* source,
1285 const content::DropData& data,
1286 blink::WebDragOperationsMask operations_allowed) {
1287 // Disallow drag-and-drop navigation for Settings windows which do not support
1288 // external navigation.
1289 if ((operations_allowed & blink::WebDragOperationLink) &&
1290 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1291 return false;
1293 return true;
1296 content::SecurityStyle Browser::GetSecurityStyle(
1297 WebContents* web_contents,
1298 content::SecurityStyleExplanations* security_style_explanations) {
1299 connection_security::SecurityInfo security_info;
1300 connection_security::GetSecurityInfoForWebContents(web_contents,
1301 &security_info);
1303 security_style_explanations->ran_insecure_content_style =
1304 connection_security::kRanInsecureContentStyle;
1305 security_style_explanations->displayed_insecure_content_style =
1306 connection_security::kDisplayedInsecureContentStyle;
1308 // Check if the page is HTTP; if so, no explanations are needed. Note
1309 // that SECURITY_STYLE_UNAUTHENTICATED does not necessarily mean that
1310 // the page is loaded over HTTP, because the security style merely
1311 // represents how the embedder wishes to display the security state of
1312 // the page, and the embedder can choose to display HTTPS page as HTTP
1313 // if it wants to (for example, displaying deprecated crypto
1314 // algorithms with the same UI treatment as HTTP pages).
1315 security_style_explanations->scheme_is_cryptographic =
1316 security_info.scheme_is_cryptographic;
1317 if (!security_info.scheme_is_cryptographic ||
1318 security_info.security_style == content::SECURITY_STYLE_UNKNOWN) {
1319 return security_info.security_style;
1322 if (security_info.sha1_deprecation_status ==
1323 connection_security::DEPRECATED_SHA1_BROKEN) {
1324 security_style_explanations->broken_explanations.push_back(
1325 content::SecurityStyleExplanation(
1326 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1),
1327 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1_DESCRIPTION)));
1328 } else if (security_info.sha1_deprecation_status ==
1329 connection_security::DEPRECATED_SHA1_WARNING) {
1330 security_style_explanations->warning_explanations.push_back(
1331 content::SecurityStyleExplanation(
1332 l10n_util::GetStringUTF8(IDS_WARNING_SHA1),
1333 l10n_util::GetStringUTF8(IDS_WARNING_SHA1_DESCRIPTION)));
1336 security_style_explanations->ran_insecure_content =
1337 security_info.mixed_content_status ==
1338 connection_security::RAN_MIXED_CONTENT ||
1339 security_info.mixed_content_status ==
1340 connection_security::RAN_AND_DISPLAYED_MIXED_CONTENT;
1341 security_style_explanations->displayed_insecure_content =
1342 security_info.mixed_content_status ==
1343 connection_security::DISPLAYED_MIXED_CONTENT ||
1344 security_info.mixed_content_status ==
1345 connection_security::RAN_AND_DISPLAYED_MIXED_CONTENT;
1347 if (net::IsCertStatusError(security_info.cert_status)) {
1348 base::string16 error_string = base::UTF8ToUTF16(net::ErrorToString(
1349 net::MapCertStatusToNetError(security_info.cert_status)));
1351 content::SecurityStyleExplanation explanation(
1352 l10n_util::GetStringUTF8(IDS_CERTIFICATE_CHAIN_ERROR),
1353 l10n_util::GetStringFUTF8(
1354 IDS_CERTIFICATE_CHAIN_ERROR_DESCRIPTION_FORMAT, error_string));
1356 if (net::IsCertStatusMinorError(security_info.cert_status))
1357 security_style_explanations->warning_explanations.push_back(explanation);
1358 else
1359 security_style_explanations->broken_explanations.push_back(explanation);
1360 } else {
1361 // If the certificate does not have errors and is not using
1362 // deprecated SHA1, then add an explanation that the certificate is
1363 // valid.
1364 if (security_info.sha1_deprecation_status ==
1365 connection_security::NO_DEPRECATED_SHA1) {
1366 security_style_explanations->secure_explanations.push_back(
1367 content::SecurityStyleExplanation(
1368 l10n_util::GetStringUTF8(IDS_VALID_SERVER_CERTIFICATE),
1369 l10n_util::GetStringUTF8(
1370 IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION)));
1374 return security_info.security_style;
1377 bool Browser::IsMouseLocked() const {
1378 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1381 void Browser::OnWindowDidShow() {
1382 if (window_has_shown_)
1383 return;
1384 window_has_shown_ = true;
1386 startup_metric_utils::RecordBrowserWindowDisplay(base::Time::Now());
1388 // Nothing to do for non-tabbed windows.
1389 if (!is_type_tabbed())
1390 return;
1392 // Show any pending global error bubble.
1393 GlobalErrorService* service =
1394 GlobalErrorServiceFactory::GetForProfile(profile());
1395 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1396 if (error)
1397 error->ShowBubbleView(this);
1400 void Browser::ShowFirstRunBubble() {
1401 window()->GetLocationBar()->ShowFirstRunBubble();
1404 ///////////////////////////////////////////////////////////////////////////////
1405 // Browser, content::WebContentsDelegate implementation:
1407 WebContents* Browser::OpenURLFromTab(WebContents* source,
1408 const OpenURLParams& params) {
1409 if (is_devtools()) {
1410 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1411 DCHECK(window);
1412 return window->OpenURLFromTab(source, params);
1415 chrome::NavigateParams nav_params(this, params.url, params.transition);
1416 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1417 nav_params.source_contents = source;
1418 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1419 if (params.user_gesture)
1420 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1421 nav_params.user_gesture = params.user_gesture;
1423 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1424 if (source)
1425 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1427 if (popup_blocker_helper) {
1428 if ((params.disposition == NEW_POPUP ||
1429 params.disposition == NEW_FOREGROUND_TAB ||
1430 params.disposition == NEW_BACKGROUND_TAB ||
1431 params.disposition == NEW_WINDOW) &&
1432 !params.user_gesture &&
1433 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1434 switches::kDisablePopupBlocking)) {
1435 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1436 WebWindowFeatures())) {
1437 return NULL;
1442 chrome::Navigate(&nav_params);
1444 return nav_params.target_contents;
1447 void Browser::NavigationStateChanged(WebContents* source,
1448 content::InvalidateTypes changed_flags) {
1449 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1450 // is fixed.
1451 tracked_objects::ScopedTracker tracking_profile1(
1452 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1453 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1454 // Only update the UI when something visible has changed.
1455 if (changed_flags)
1456 ScheduleUIUpdate(source, changed_flags);
1458 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1459 // is fixed.
1460 tracked_objects::ScopedTracker tracking_profile2(
1461 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1462 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1463 // We can synchronously update commands since they will only change once per
1464 // navigation, so we don't have to worry about flickering. We do, however,
1465 // need to update the command state early on load to always present usable
1466 // actions in the face of slow-to-commit pages.
1467 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1468 content::INVALIDATE_TYPE_LOAD))
1469 command_controller_->TabStateChanged();
1471 if (hosted_app_controller_)
1472 hosted_app_controller_->UpdateLocationBarVisibility(true);
1475 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1476 // When the current tab's SSL state changes, we need to update the URL
1477 // bar to reflect the new state.
1478 DCHECK(source);
1479 if (tab_strip_model_->GetActiveWebContents() == source)
1480 UpdateToolbar(false);
1483 void Browser::AddNewContents(WebContents* source,
1484 WebContents* new_contents,
1485 WindowOpenDisposition disposition,
1486 const gfx::Rect& initial_rect,
1487 bool user_gesture,
1488 bool* was_blocked) {
1489 chrome::AddWebContents(this, source, new_contents, disposition, initial_rect,
1490 user_gesture, was_blocked);
1493 void Browser::ActivateContents(WebContents* contents) {
1494 tab_strip_model_->ActivateTabAt(
1495 tab_strip_model_->GetIndexOfWebContents(contents), false);
1496 window_->Activate();
1499 void Browser::DeactivateContents(WebContents* contents) {
1500 window_->Deactivate();
1503 void Browser::LoadingStateChanged(WebContents* source,
1504 bool to_different_document) {
1505 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1506 window_->UpdateTitleBar();
1508 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1509 if (source == selected_contents) {
1510 bool is_loading = source->IsLoading() && to_different_document;
1511 command_controller_->LoadingStateChanged(is_loading, false);
1512 if (GetStatusBubble()) {
1513 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1514 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1519 void Browser::CloseContents(WebContents* source) {
1520 bool can_close_contents;
1521 if (IsFastTabUnloadEnabled())
1522 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1523 else
1524 can_close_contents = unload_controller_->CanCloseContents(source);
1526 if (can_close_contents)
1527 chrome::CloseWebContents(this, source, true);
1530 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1531 if (!IsPopupOrPanel(source)) {
1532 NOTREACHED() << "moving invalid browser type";
1533 return;
1535 window_->SetBounds(pos);
1538 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1539 return is_type_popup();
1542 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1543 if (!GetStatusBubble())
1544 return;
1546 if (source == tab_strip_model_->GetActiveWebContents()) {
1547 PrefService* prefs = profile_->GetPrefs();
1548 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1552 void Browser::ContentsMouseEvent(
1553 WebContents* source, const gfx::Point& location, bool motion) {
1554 if (!GetStatusBubble())
1555 return;
1557 if (source == tab_strip_model_->GetActiveWebContents()) {
1558 GetStatusBubble()->MouseMoved(location, !motion);
1559 if (!motion)
1560 GetStatusBubble()->SetURL(GURL(), std::string());
1564 void Browser::ContentsZoomChange(bool zoom_in) {
1565 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1568 bool Browser::TakeFocus(content::WebContents* source,
1569 bool reverse) {
1570 content::NotificationService::current()->Notify(
1571 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1572 content::Source<Browser>(this),
1573 content::NotificationService::NoDetails());
1574 return false;
1577 gfx::Rect Browser::GetRootWindowResizerRect() const {
1578 return window_->GetRootWindowResizerRect();
1581 void Browser::BeforeUnloadFired(WebContents* web_contents,
1582 bool proceed,
1583 bool* proceed_to_fire_unload) {
1584 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1585 proceed, proceed_to_fire_unload))
1586 return;
1588 if (IsFastTabUnloadEnabled()) {
1589 *proceed_to_fire_unload =
1590 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1591 } else {
1592 *proceed_to_fire_unload =
1593 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1597 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1598 const content::NavigationEntry* entry =
1599 source->GetController().GetActiveEntry();
1600 if (entry) {
1601 GURL url = entry->GetURL();
1602 GURL virtual_url = entry->GetVirtualURL();
1603 if ((url.SchemeIs(content::kChromeUIScheme) &&
1604 url.host() == chrome::kChromeUINewTabHost) ||
1605 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1606 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1607 return true;
1611 return search::NavEntryIsInstantNTP(source, entry);
1614 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1615 DCHECK(source);
1616 chrome::ViewSource(this, source);
1619 void Browser::ViewSourceForFrame(WebContents* source,
1620 const GURL& frame_url,
1621 const content::PageState& frame_page_state) {
1622 DCHECK(source);
1623 chrome::ViewSource(this, source, frame_url, frame_page_state);
1626 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1627 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1628 source);
1631 bool Browser::ShouldCreateWebContents(
1632 WebContents* web_contents,
1633 int route_id,
1634 int main_frame_route_id,
1635 WindowContainerType window_container_type,
1636 const std::string& frame_name,
1637 const GURL& target_url,
1638 const std::string& partition_id,
1639 content::SessionStorageNamespace* session_storage_namespace) {
1640 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1641 // If a BackgroundContents is created, suppress the normal WebContents.
1642 return !MaybeCreateBackgroundContents(route_id,
1643 main_frame_route_id,
1644 web_contents,
1645 frame_name,
1646 target_url,
1647 partition_id,
1648 session_storage_namespace);
1651 return true;
1654 void Browser::WebContentsCreated(WebContents* source_contents,
1655 int opener_render_frame_id,
1656 const std::string& frame_name,
1657 const GURL& target_url,
1658 WebContents* new_contents) {
1659 // Adopt the WebContents now, so all observers are in place, as the network
1660 // requests for its initial navigation will start immediately. The WebContents
1661 // will later be inserted into this browser using Browser::Navigate via
1662 // AddNewContents.
1663 TabHelpers::AttachTabHelpers(new_contents);
1665 // Make the tab show up in the task manager.
1666 task_management::WebContentsTags::CreateForTabContents(new_contents);
1668 // Notify.
1669 RetargetingDetails details;
1670 details.source_web_contents = source_contents;
1671 details.source_render_frame_id = opener_render_frame_id;
1672 details.target_url = target_url;
1673 details.target_web_contents = new_contents;
1674 details.not_yet_in_tabstrip = true;
1675 content::NotificationService::current()->Notify(
1676 chrome::NOTIFICATION_RETARGETING,
1677 content::Source<Profile>(profile_),
1678 content::Details<RetargetingDetails>(&details));
1681 void Browser::RendererUnresponsive(WebContents* source) {
1682 // Ignore hangs if a tab is blocked.
1683 int index = tab_strip_model_->GetIndexOfWebContents(source);
1684 DCHECK_NE(TabStripModel::kNoTab, index);
1685 if (tab_strip_model_->IsTabBlocked(index))
1686 return;
1688 TabDialogs::FromWebContents(source)->ShowHungRendererDialog();
1691 void Browser::RendererResponsive(WebContents* source) {
1692 TabDialogs::FromWebContents(source)->HideHungRendererDialog();
1695 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1696 if (web_contents == tab_strip_model_->GetActiveWebContents())
1697 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1700 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1701 WebContents* source) {
1702 return app_modal::JavaScriptDialogManager::GetInstance();
1705 content::ColorChooser* Browser::OpenColorChooser(
1706 WebContents* web_contents,
1707 SkColor initial_color,
1708 const std::vector<content::ColorSuggestion>& suggestions) {
1709 return chrome::ShowColorChooser(web_contents, initial_color);
1712 void Browser::RunFileChooser(WebContents* web_contents,
1713 const content::FileChooserParams& params) {
1714 FileSelectHelper::RunFileChooser(web_contents, params);
1717 void Browser::EnumerateDirectory(WebContents* web_contents,
1718 int request_id,
1719 const base::FilePath& path) {
1720 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1723 bool Browser::EmbedsFullscreenWidget() const {
1724 return true;
1727 void Browser::EnterFullscreenModeForTab(WebContents* web_contents,
1728 const GURL& origin) {
1729 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1730 web_contents, origin);
1733 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1734 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1735 web_contents);
1738 bool Browser::IsFullscreenForTabOrPending(
1739 const WebContents* web_contents) const {
1740 return exclusive_access_manager_->fullscreen_controller()
1741 ->IsFullscreenForTabOrPending(web_contents);
1744 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1745 const std::string& protocol,
1746 const GURL& url,
1747 bool user_gesture) {
1748 content::BrowserContext* context = web_contents->GetBrowserContext();
1749 if (context->IsOffTheRecord())
1750 return;
1752 ProtocolHandler handler =
1753 ProtocolHandler::CreateProtocolHandler(protocol, url);
1755 ProtocolHandlerRegistry* registry =
1756 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1757 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1758 return;
1760 TabSpecificContentSettings* tab_content_settings =
1761 TabSpecificContentSettings::FromWebContents(web_contents);
1762 if (!user_gesture && window_) {
1763 tab_content_settings->set_pending_protocol_handler(handler);
1764 tab_content_settings->set_previous_protocol_handler(
1765 registry->GetHandlerFor(handler.protocol()));
1766 window_->GetLocationBar()->UpdateContentSettingsIcons();
1767 return;
1770 // Make sure content-setting icon is turned off in case the page does
1771 // ungestured and gestured RPH calls.
1772 if (window_) {
1773 tab_content_settings->ClearPendingProtocolHandler();
1774 window_->GetLocationBar()->UpdateContentSettingsIcons();
1777 PermissionBubbleManager* bubble_manager =
1778 PermissionBubbleManager::FromWebContents(web_contents);
1779 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1780 bubble_manager->AddRequest(
1781 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1782 url, user_gesture));
1783 } else {
1784 RegisterProtocolHandlerInfoBarDelegate::Create(
1785 InfoBarService::FromWebContents(web_contents), registry, handler);
1789 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1790 const std::string& protocol,
1791 const GURL& url,
1792 bool user_gesture) {
1793 // user_gesture will be used in case we decide to have confirmation bubble
1794 // for user while un-registering the handler.
1795 content::BrowserContext* context = web_contents->GetBrowserContext();
1796 if (context->IsOffTheRecord())
1797 return;
1799 ProtocolHandler handler =
1800 ProtocolHandler::CreateProtocolHandler(protocol, url);
1802 ProtocolHandlerRegistry* registry =
1803 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1804 registry->RemoveHandler(handler);
1807 void Browser::UpdatePreferredSize(WebContents* source,
1808 const gfx::Size& pref_size) {
1809 window_->UpdatePreferredSize(source, pref_size);
1812 void Browser::ResizeDueToAutoResize(WebContents* source,
1813 const gfx::Size& new_size) {
1814 window_->ResizeDueToAutoResize(source, new_size);
1817 void Browser::FindReply(WebContents* web_contents,
1818 int request_id,
1819 int number_of_matches,
1820 const gfx::Rect& selection_rect,
1821 int active_match_ordinal,
1822 bool final_update) {
1823 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1824 if (!find_tab_helper)
1825 return;
1827 find_tab_helper->HandleFindReply(request_id,
1828 number_of_matches,
1829 selection_rect,
1830 active_match_ordinal,
1831 final_update);
1834 void Browser::RequestToLockMouse(WebContents* web_contents,
1835 bool user_gesture,
1836 bool last_unlocked_by_target) {
1837 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
1838 web_contents, user_gesture, last_unlocked_by_target);
1841 void Browser::LostMouseLock() {
1842 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
1845 void Browser::RequestMediaAccessPermission(
1846 content::WebContents* web_contents,
1847 const content::MediaStreamRequest& request,
1848 const content::MediaResponseCallback& callback) {
1849 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1852 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1853 const GURL& security_origin,
1854 content::MediaStreamType type) {
1855 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1858 bool Browser::RequestPpapiBrokerPermission(
1859 WebContents* web_contents,
1860 const GURL& url,
1861 const base::FilePath& plugin_path,
1862 const base::Callback<void(bool)>& callback) {
1863 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1864 return true;
1867 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1868 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1869 // would disappear on non-NTP pages, resulting in a bigger size for the new
1870 // render view.
1871 gfx::Size size = web_contents->GetContainerBounds().size();
1872 // Don't change render view size if bookmark bar is currently not detached,
1873 // or there's no pending entry, or navigating to a NTP page.
1874 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1875 return size;
1876 const NavigationEntry* pending_entry =
1877 web_contents->GetController().GetPendingEntry();
1878 if (pending_entry &&
1879 !search::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1880 size.Enlarge(
1881 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1883 return size;
1886 ///////////////////////////////////////////////////////////////////////////////
1887 // Browser, CoreTabHelperDelegate implementation:
1889 void Browser::SwapTabContents(content::WebContents* old_contents,
1890 content::WebContents* new_contents,
1891 bool did_start_load,
1892 bool did_finish_load) {
1893 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1894 DCHECK_NE(TabStripModel::kNoTab, index);
1895 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1898 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1899 return chrome::CanReload(this);
1902 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1903 return chrome::CanSavePage(this);
1906 ///////////////////////////////////////////////////////////////////////////////
1907 // Browser, SearchEngineTabHelperDelegate implementation:
1909 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1910 Profile* profile) {
1911 window()->ConfirmAddSearchProvider(template_url, profile);
1914 ///////////////////////////////////////////////////////////////////////////////
1915 // Browser, SearchTabHelperDelegate implementation:
1917 void Browser::NavigateOnThumbnailClick(const GURL& url,
1918 WindowOpenDisposition disposition,
1919 content::WebContents* source_contents) {
1920 DCHECK(source_contents);
1921 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1922 // gets called to handle clicks in the new tab page (to navigate to most
1923 // visited item URLs) and in the search results page (to navigate to
1924 // privileged destinations (e.g. chrome://URLs)).
1926 // TODO(kmadhusu): Page transitions to privileged destinations should be
1927 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1928 chrome::NavigateParams params(this, url,
1929 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1930 params.referrer = content::Referrer();
1931 params.source_contents = source_contents;
1932 params.disposition = disposition;
1933 params.is_renderer_initiated = false;
1934 params.initiating_profile = profile_;
1935 chrome::Navigate(&params);
1938 void Browser::OnWebContentsInstantSupportDisabled(
1939 const content::WebContents* web_contents) {
1940 DCHECK(web_contents);
1941 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1942 UpdateToolbar(false);
1945 OmniboxView* Browser::GetOmniboxView() {
1946 return window_->GetLocationBar()->GetOmniboxView();
1949 std::set<std::string> Browser::GetOpenUrls() {
1950 scoped_refptr<history::TopSites> top_sites =
1951 TopSitesFactory::GetForProfile(profile_);
1952 if (!top_sites) // NULL for Incognito profiles.
1953 return std::set<std::string>();
1955 std::set<std::string> open_urls;
1956 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1957 return open_urls;
1960 ///////////////////////////////////////////////////////////////////////////////
1961 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1963 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1964 bool blocked) {
1965 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1966 if (index == TabStripModel::kNoTab) {
1967 NOTREACHED();
1968 return;
1970 tab_strip_model_->SetTabBlocked(index, blocked);
1971 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1972 web_contents->Focus();
1975 web_modal::WebContentsModalDialogHost*
1976 Browser::GetWebContentsModalDialogHost() {
1977 return window_->GetWebContentsModalDialogHost();
1980 ///////////////////////////////////////////////////////////////////////////////
1981 // Browser, BookmarkTabHelperDelegate implementation:
1983 void Browser::URLStarredChanged(content::WebContents* web_contents,
1984 bool starred) {
1985 if (web_contents == tab_strip_model_->GetActiveWebContents())
1986 window_->SetStarredState(starred);
1989 ///////////////////////////////////////////////////////////////////////////////
1990 // Browser, ZoomObserver implementation:
1992 void Browser::OnZoomChanged(
1993 const ui_zoom::ZoomController::ZoomChangedEventData& data) {
1994 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1995 window_->ZoomChangedForActiveTab(data.can_show_bubble);
1996 // Change the zoom commands state based on the zoom state
1997 command_controller_->ZoomStateChanged();
2001 ///////////////////////////////////////////////////////////////////////////////
2002 // Browser, ui::SelectFileDialog::Listener implementation:
2004 void Browser::FileSelected(const base::FilePath& path, int index,
2005 void* params) {
2006 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
2009 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
2010 int index,
2011 void* params) {
2012 profile_->set_last_selected_directory(file_info.file_path.DirName());
2014 GURL url = net::FilePathToFileURL(file_info.local_path);
2016 #if defined(OS_CHROMEOS)
2017 const GURL external_url =
2018 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
2019 if (!external_url.is_empty())
2020 url = external_url;
2021 #endif
2023 if (url.is_empty())
2024 return;
2026 OpenURL(OpenURLParams(
2027 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
2030 ///////////////////////////////////////////////////////////////////////////////
2031 // Browser, content::NotificationObserver implementation:
2033 void Browser::Observe(int type,
2034 const content::NotificationSource& source,
2035 const content::NotificationDetails& details) {
2036 switch (type) {
2037 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2038 Profile* profile = content::Source<Profile>(source).ptr();
2039 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
2040 window()->GetLocationBar()->UpdatePageActions();
2041 break;
2044 #if defined(ENABLE_THEMES)
2045 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2046 window()->UserChangedTheme();
2047 break;
2048 #endif
2050 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2051 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2052 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2053 LocationBar* location_bar = window()->GetLocationBar();
2054 if (location_bar)
2055 location_bar->UpdateContentSettingsIcons();
2057 break;
2060 default:
2061 NOTREACHED() << "Got a notification we didn't register for.";
2065 #if defined(ENABLE_EXTENSIONS)
2066 ///////////////////////////////////////////////////////////////////////////////
2067 // Browser, extensions::ExtensionRegistryObserver implementation:
2069 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
2070 const extensions::Extension* extension,
2071 extensions::UninstallReason reason) {
2072 // During window creation on Windows we may end up calling into
2073 // SHAppBarMessage, which internally spawns a nested message loop.This
2074 // makes it possible for us to end up here before window creation has
2075 // completed, at which point window_ is NULL. See 94752 for details.
2077 if (window() && window()->GetLocationBar())
2078 window()->GetLocationBar()->UpdatePageActions();
2081 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2082 const extensions::Extension* extension) {
2083 command_controller_->ExtensionStateChanged();
2086 void Browser::OnExtensionUnloaded(
2087 content::BrowserContext* browser_context,
2088 const extensions::Extension* extension,
2089 extensions::UnloadedExtensionInfo::Reason reason) {
2090 command_controller_->ExtensionStateChanged();
2091 if (window()->GetLocationBar())
2092 window()->GetLocationBar()->UpdatePageActions();
2094 // Close any tabs from the unloaded extension, unless it's terminated,
2095 // in which case let the sad tabs remain.
2096 // Also, if tab is muted and the cause is the unloaded extension, unmute it.
2097 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2098 // Iterate backwards as we may remove items while iterating.
2099 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2100 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2101 // Two cases are handled here:
2103 // - The scheme check is for when an extension page is loaded in a
2104 // tab, e.g. chrome-extension://id/page.html.
2105 // - The extension_app check is for apps, which can have non-extension
2106 // schemes, e.g. https://mail.google.com if you have the Gmail app
2107 // installed.
2108 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2109 web_contents->GetURL().host() == extension->id()) ||
2110 (extensions::TabHelper::FromWebContents(web_contents)
2111 ->extension_app() == extension)) {
2112 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2113 } else {
2114 chrome::UnmuteIfMutedByExtension(web_contents, extension->id());
2119 #endif // defined(ENABLE_EXTENSIONS)
2121 ///////////////////////////////////////////////////////////////////////////////
2122 // Browser, translate::ContentTranslateDriver::Observer implementation:
2124 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2125 DCHECK(source);
2126 if (tab_strip_model_->GetActiveWebContents() == source) {
2127 window_->SetTranslateIconToggled(
2128 ChromeTranslateClient::FromWebContents(
2129 source)->GetLanguageState().IsPageTranslated());
2133 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2134 DCHECK(source);
2135 if (tab_strip_model_->GetActiveWebContents() == source)
2136 UpdateToolbar(false);
2139 ///////////////////////////////////////////////////////////////////////////////
2140 // Browser, Command and state updating (private):
2142 void Browser::OnDevToolsDisabledChanged() {
2143 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2144 content::DevToolsAgentHost::DetachAllClients();
2147 ///////////////////////////////////////////////////////////////////////////////
2148 // Browser, UI update coalescing and handling (private):
2150 void Browser::UpdateToolbar(bool should_restore_state) {
2151 window_->UpdateToolbar(should_restore_state ?
2152 tab_strip_model_->GetActiveWebContents() : NULL);
2155 void Browser::ScheduleUIUpdate(WebContents* source,
2156 unsigned changed_flags) {
2157 DCHECK(source);
2158 int index = tab_strip_model_->GetIndexOfWebContents(source);
2159 DCHECK_NE(TabStripModel::kNoTab, index);
2161 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2162 // is fixed.
2163 tracked_objects::ScopedTracker tracking_profile1(
2164 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2165 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2166 // Do some synchronous updates.
2167 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2168 if (source == tab_strip_model_->GetActiveWebContents()) {
2169 // Only update the URL for the current tab. Note that we do not update
2170 // the navigation commands since those would have already been updated
2171 // synchronously by NavigationStateChanged.
2172 UpdateToolbar(false);
2173 } else {
2174 // Clear the saved tab state for the tab that navigated, so that we don't
2175 // restore any user text after the old URL has been invalidated (e.g.,
2176 // after a new navigation commits in that tab while unfocused).
2177 window_->ResetToolbarTabState(source);
2179 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2182 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2183 // is fixed.
2184 tracked_objects::ScopedTracker tracking_profile2(
2185 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2186 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2187 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2188 // Update the loading state synchronously. This is so the throbber will
2189 // immediately start/stop, which gives a more snappy feel. We want to do
2190 // this for any tab so they start & stop quickly.
2191 tab_strip_model_->UpdateWebContentsStateAt(
2192 tab_strip_model_->GetIndexOfWebContents(source),
2193 TabStripModelObserver::LOADING_ONLY);
2194 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2195 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2196 // changed_flags.
2199 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2200 // To correctly calculate whether the title changed while not loading
2201 // we need to process the update synchronously. This state only matters for
2202 // the TabStripModel, so we notify the TabStripModel now and notify others
2203 // asynchronously.
2204 tab_strip_model_->UpdateWebContentsStateAt(
2205 tab_strip_model_->GetIndexOfWebContents(source),
2206 TabStripModelObserver::TITLE_NOT_LOADING);
2209 // If the only updates were synchronously handled above, we're done.
2210 if (changed_flags == 0)
2211 return;
2213 // Save the dirty bits.
2214 scheduled_updates_[source] |= changed_flags;
2216 if (!chrome_updater_factory_.HasWeakPtrs()) {
2217 // No task currently scheduled, start another.
2218 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2219 FROM_HERE, base::Bind(&Browser::ProcessPendingUIUpdates,
2220 chrome_updater_factory_.GetWeakPtr()),
2221 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2225 void Browser::ProcessPendingUIUpdates() {
2226 #ifndef NDEBUG
2227 // Validate that all tabs we have pending updates for exist. This is scary
2228 // because the pending list must be kept in sync with any detached or
2229 // deleted tabs.
2230 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2231 i != scheduled_updates_.end(); ++i) {
2232 bool found = false;
2233 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2234 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2235 found = true;
2236 break;
2239 DCHECK(found);
2241 #endif
2243 chrome_updater_factory_.InvalidateWeakPtrs();
2245 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2246 // is fixed.
2247 tracked_objects::ScopedTracker tracking_profile1(
2248 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2249 "467185 Browser::ProcessPendingUIUpdates1"));
2251 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2252 i != scheduled_updates_.end(); ++i) {
2253 // Do not dereference |contents|, it may be out-of-date!
2254 const WebContents* contents = i->first;
2255 unsigned flags = i->second;
2257 if (contents == tab_strip_model_->GetActiveWebContents()) {
2258 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2259 // is fixed.
2260 tracked_objects::ScopedTracker tracking_profile2(
2261 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2262 "467185 Browser::ProcessPendingUIUpdates2"));
2264 // Updates that only matter when the tab is selected go here.
2266 // Updating the URL happens synchronously in ScheduleUIUpdate.
2267 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2268 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2269 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2272 if (flags & (content::INVALIDATE_TYPE_TAB |
2273 content::INVALIDATE_TYPE_TITLE)) {
2274 window_->UpdateTitleBar();
2278 // Updates that don't depend upon the selected state go here.
2279 if (flags &
2280 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2281 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2282 // is fixed.
2283 tracked_objects::ScopedTracker tracking_profile3(
2284 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2285 "467185 Browser::ProcessPendingUIUpdates3"));
2286 tab_strip_model_->UpdateWebContentsStateAt(
2287 tab_strip_model_->GetIndexOfWebContents(contents),
2288 TabStripModelObserver::ALL);
2291 // Update the bookmark bar. It may happen that the tab is crashed, and if
2292 // so, the bookmark bar should be hidden.
2293 if (flags & content::INVALIDATE_TYPE_TAB) {
2294 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2295 // is fixed.
2296 tracked_objects::ScopedTracker tracking_profile4(
2297 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2298 "467185 Browser::ProcessPendingUIUpdates4"));
2299 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2302 // We don't need to process INVALIDATE_STATE, since that's not visible.
2305 scheduled_updates_.clear();
2308 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2309 if (!contents)
2310 return;
2312 UpdateMap::iterator i = scheduled_updates_.find(contents);
2313 if (i != scheduled_updates_.end())
2314 scheduled_updates_.erase(i);
2317 ///////////////////////////////////////////////////////////////////////////////
2318 // Browser, Getters for UI (private):
2320 StatusBubble* Browser::GetStatusBubble() {
2321 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2322 if (chrome::IsRunningInAppMode())
2323 return NULL;
2325 return window_ ? window_->GetStatusBubble() : NULL;
2328 ///////////////////////////////////////////////////////////////////////////////
2329 // Browser, Session restore functions (private):
2331 void Browser::SyncHistoryWithTabs(int index) {
2332 SessionService* session_service =
2333 SessionServiceFactory::GetForProfileIfExisting(profile());
2334 if (session_service) {
2335 for (int i = index; i < tab_strip_model_->count(); ++i) {
2336 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2337 if (web_contents) {
2338 SessionTabHelper* session_tab_helper =
2339 SessionTabHelper::FromWebContents(web_contents);
2340 session_service->SetTabIndexInWindow(
2341 session_id(), session_tab_helper->session_id(), i);
2342 session_service->SetPinnedState(
2343 session_id(),
2344 session_tab_helper->session_id(),
2345 tab_strip_model_->IsTabPinned(i));
2351 ///////////////////////////////////////////////////////////////////////////////
2352 // Browser, In-progress download termination handling (private):
2354 bool Browser::CanCloseWithInProgressDownloads() {
2355 // If we've prompted, we need to hear from the user before we
2356 // can close.
2357 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2358 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2360 int num_downloads_blocking;
2361 Browser::DownloadClosePreventionType dialog_type =
2362 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2363 if (dialog_type == DOWNLOAD_CLOSE_OK)
2364 return true;
2366 // Closing this window will kill some downloads; prompt to make sure
2367 // that's ok.
2368 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2369 window_->ConfirmBrowserCloseWithPendingDownloads(
2370 num_downloads_blocking,
2371 dialog_type,
2372 false,
2373 base::Bind(&Browser::InProgressDownloadResponse,
2374 weak_factory_.GetWeakPtr()));
2376 // Return false so the browser does not close. We'll close if the user
2377 // confirms in the dialog.
2378 return false;
2381 ///////////////////////////////////////////////////////////////////////////////
2382 // Browser, Assorted utility functions (private):
2384 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2385 Browser* delegate = set_delegate ? this : NULL;
2386 // WebContents...
2387 web_contents->SetDelegate(delegate);
2389 // ...and all the helpers.
2390 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2391 WebContentsModalDialogManager::FromWebContents(web_contents)->
2392 SetDelegate(delegate);
2393 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2394 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2395 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2396 translate::ContentTranslateDriver& content_translate_driver =
2397 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2398 if (delegate) {
2399 ui_zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2400 content_translate_driver.AddObserver(this);
2401 } else {
2402 ui_zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(
2403 this);
2404 content_translate_driver.RemoveObserver(this);
2408 void Browser::CloseFrame() {
2409 window_->Close();
2412 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2413 int index,
2414 DetachType type) {
2415 if (type == DETACH_TYPE_DETACH) {
2416 // Save the current location bar state, but only if the tab being detached
2417 // is the selected tab. Because saving state can conditionally revert the
2418 // location bar, saving the current tab's location bar state to a
2419 // non-selected tab can corrupt both tabs.
2420 if (contents == tab_strip_model_->GetActiveWebContents()) {
2421 LocationBar* location_bar = window()->GetLocationBar();
2422 if (location_bar)
2423 location_bar->SaveStateToContents(contents);
2426 if (!tab_strip_model_->closing_all())
2427 SyncHistoryWithTabs(0);
2430 SetAsDelegate(contents, false);
2431 RemoveScheduledUpdatesFor(contents);
2433 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2434 find_bar_controller_->ChangeWebContents(NULL);
2437 // Stop observing search model changes for this tab.
2438 search_delegate_->OnTabDetached(contents);
2440 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2441 if (interstitial_observers_[i]->web_contents() != contents)
2442 continue;
2444 delete interstitial_observers_[i];
2445 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2446 return;
2450 bool Browser::SupportsLocationBar() const {
2451 // Tabbed browser always show a location bar.
2452 if (is_type_tabbed())
2453 return true;
2455 // Non-app windows that aren't tabbed or system windows should always show a
2456 // location bar, unless they are from a trusted source.
2457 if (!is_app())
2458 return !is_trusted_source();
2460 if (hosted_app_controller_)
2461 return hosted_app_controller_->SupportsLocationBar();
2463 return false;
2466 bool Browser::ShouldUseWebAppFrame() const {
2467 // Only use the web app frame for apps in ash, and only if the web app frame
2468 // is enabled.
2469 if (!is_app())
2470 return false;
2472 if (hosted_app_controller_)
2473 return hosted_app_controller_->should_use_web_app_frame();
2475 return false;
2478 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2479 bool check_fullscreen) const {
2480 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2482 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2484 if (is_type_tabbed())
2485 features |= FEATURE_BOOKMARKBAR;
2487 if (!hide_ui_for_fullscreen) {
2488 if (!is_type_tabbed())
2489 features |= FEATURE_TITLEBAR;
2491 if (is_type_tabbed())
2492 features |= FEATURE_TABSTRIP;
2494 if (is_type_tabbed())
2495 features |= FEATURE_TOOLBAR;
2497 if (SupportsLocationBar())
2498 features |= FEATURE_LOCATIONBAR;
2500 if (ShouldUseWebAppFrame())
2501 features |= FEATURE_WEBAPPFRAME;
2503 return !!(features & feature);
2506 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2507 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2508 // fixed.
2509 tracked_objects::ScopedTracker tracking_profile1(
2510 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2511 "467185 Browser::UpdateBookmarkBarState1"));
2512 BookmarkBar::State state;
2513 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2514 // mode, unless on the new tab page.
2515 if (profile_->IsGuestSession()) {
2516 state = BookmarkBar::HIDDEN;
2517 } else if (browser_defaults::bookmarks_enabled &&
2518 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2519 !ShouldHideUIForFullscreen()) {
2520 state = BookmarkBar::SHOW;
2521 } else {
2522 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2523 // is fixed.
2524 tracked_objects::ScopedTracker tracking_profile2(
2525 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2526 "467185 Browser::UpdateBookmarkBarState2"));
2527 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2528 BookmarkTabHelper* bookmark_tab_helper =
2529 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2530 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2531 state = BookmarkBar::DETACHED;
2532 else
2533 state = BookmarkBar::HIDDEN;
2536 if (state == bookmark_bar_state_)
2537 return;
2539 bookmark_bar_state_ = state;
2541 if (!window_)
2542 return; // This is called from the constructor when window_ is NULL.
2544 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2545 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2546 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2547 // end up querying state once they process the tab switch.
2548 return;
2551 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2552 // fixed.
2553 tracked_objects::ScopedTracker tracking_profile3(
2554 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2555 "467185 Browser::UpdateBookmarkBarState3"));
2557 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2558 window_->BookmarkBarStateChanged(should_animate ?
2559 BookmarkBar::ANIMATE_STATE_CHANGE :
2560 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2563 bool Browser::ShouldHideUIForFullscreen() const {
2564 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2565 // keep the controls in a slide-down panel.
2566 return window_ && window_->ShouldHideUIForFullscreen();
2569 bool Browser::MaybeCreateBackgroundContents(
2570 int route_id,
2571 int main_frame_route_id,
2572 WebContents* opener_web_contents,
2573 const std::string& frame_name,
2574 const GURL& target_url,
2575 const std::string& partition_id,
2576 content::SessionStorageNamespace* session_storage_namespace) {
2577 GURL opener_url = opener_web_contents->GetURL();
2578 ExtensionService* extensions_service =
2579 extensions::ExtensionSystem::Get(profile_)->extension_service();
2581 if (!opener_url.is_valid() ||
2582 frame_name.empty() ||
2583 !extensions_service ||
2584 !extensions_service->is_ready())
2585 return false;
2587 // Only hosted apps have web extents, so this ensures that only hosted apps
2588 // can create BackgroundContents. We don't have to check for background
2589 // permission as that is checked in RenderMessageFilter when the CreateWindow
2590 // message is processed.
2591 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
2592 ->enabled_extensions()
2593 .GetHostedAppByURL(opener_url);
2594 if (!extension)
2595 return false;
2597 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2598 BackgroundContentsService* service =
2599 BackgroundContentsServiceFactory::GetForProfile(profile_);
2600 if (!service)
2601 return false;
2603 // Ensure that we're trying to open this from the extension's process.
2604 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2605 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2606 if (!opener_site_instance->GetProcess() ||
2607 !process_map->Contains(
2608 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2609 return false;
2612 // Only allow a single background contents per app.
2613 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2614 BackgroundContents* existing =
2615 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2616 if (existing) {
2617 // For non-scriptable background contents, ignore the request altogether,
2618 // (returning true, so that a regular WebContents isn't created either).
2619 if (!allow_js_access)
2620 return true;
2621 // For scriptable background pages, if one already exists, close it (even
2622 // if it was specified in the manifest).
2623 delete existing;
2626 // If script access is not allowed, create the the background contents in a
2627 // new SiteInstance, so that a separate process is used.
2628 scoped_refptr<content::SiteInstance> site_instance =
2629 allow_js_access ?
2630 opener_site_instance :
2631 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2633 // Passed all the checks, so this should be created as a BackgroundContents.
2634 BackgroundContents* contents =
2635 service->CreateBackgroundContents(site_instance.get(),
2636 route_id,
2637 main_frame_route_id,
2638 profile_,
2639 frame_name,
2640 base::ASCIIToUTF16(extension->id()),
2641 partition_id,
2642 session_storage_namespace);
2644 // When a separate process is used, the original renderer cannot access the
2645 // new window later, thus we need to navigate the window now.
2646 if (contents && !allow_js_access) {
2647 contents->web_contents()->GetController().LoadURL(
2648 target_url,
2649 content::Referrer(),
2650 ui::PAGE_TRANSITION_LINK,
2651 std::string()); // No extra headers.
2654 return contents != NULL;