Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob55db7f5513835ce64bee0cafeef541dc48f4b51e
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/logging.h"
19 #include "base/metrics/histogram.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/process/process_info.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/time/time.h"
30 #include "chrome/app/chrome_command_ids.h"
31 #include "chrome/browser/app_mode/app_mode_utils.h"
32 #include "chrome/browser/autofill/personal_data_manager_factory.h"
33 #include "chrome/browser/background/background_contents.h"
34 #include "chrome/browser/background/background_contents_service.h"
35 #include "chrome/browser/background/background_contents_service_factory.h"
36 #include "chrome/browser/browser_process.h"
37 #include "chrome/browser/browser_shutdown.h"
38 #include "chrome/browser/browsing_data/browsing_data_helper.h"
39 #include "chrome/browser/browsing_data/browsing_data_remover.h"
40 #include "chrome/browser/character_encoding.h"
41 #include "chrome/browser/chrome_notification_types.h"
42 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
43 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
44 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
45 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
46 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
47 #include "chrome/browser/defaults.h"
48 #include "chrome/browser/devtools/devtools_toggle_action.h"
49 #include "chrome/browser/devtools/devtools_window.h"
50 #include "chrome/browser/download/download_item_model.h"
51 #include "chrome/browser/download/download_service.h"
52 #include "chrome/browser/download/download_service_factory.h"
53 #include "chrome/browser/download/download_shelf.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
55 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
56 #include "chrome/browser/extensions/browser_extension_window_controller.h"
57 #include "chrome/browser/extensions/extension_service.h"
58 #include "chrome/browser/extensions/extension_ui_util.h"
59 #include "chrome/browser/extensions/extension_util.h"
60 #include "chrome/browser/extensions/tab_helper.h"
61 #include "chrome/browser/favicon/favicon_tab_helper.h"
62 #include "chrome/browser/file_select_helper.h"
63 #include "chrome/browser/first_run/first_run.h"
64 #include "chrome/browser/history/top_sites_factory.h"
65 #include "chrome/browser/infobars/infobar_service.h"
66 #include "chrome/browser/lifetime/application_lifetime.h"
67 #include "chrome/browser/notifications/notification_ui_manager.h"
68 #include "chrome/browser/pepper_broker_infobar_delegate.h"
69 #include "chrome/browser/prefs/incognito_mode_prefs.h"
70 #include "chrome/browser/profiles/profile.h"
71 #include "chrome/browser/profiles/profile_destroyer.h"
72 #include "chrome/browser/profiles/profile_metrics.h"
73 #include "chrome/browser/repost_form_warning_controller.h"
74 #include "chrome/browser/search/search.h"
75 #include "chrome/browser/sessions/session_service.h"
76 #include "chrome/browser/sessions/session_service_factory.h"
77 #include "chrome/browser/sessions/session_tab_helper.h"
78 #include "chrome/browser/sessions/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/themes/theme_service.h"
86 #include "chrome/browser/themes/theme_service_factory.h"
87 #include "chrome/browser/translate/chrome_translate_client.h"
88 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
89 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
90 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
91 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
92 #include "chrome/browser/ui/browser_command_controller.h"
93 #include "chrome/browser/ui/browser_commands.h"
94 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
95 #include "chrome/browser/ui/browser_dialogs.h"
96 #include "chrome/browser/ui/browser_finder.h"
97 #include "chrome/browser/ui/browser_instant_controller.h"
98 #include "chrome/browser/ui/browser_iterator.h"
99 #include "chrome/browser/ui/browser_list.h"
100 #include "chrome/browser/ui/browser_navigator.h"
101 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
102 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
103 #include "chrome/browser/ui/browser_tabstrip.h"
104 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
105 #include "chrome/browser/ui/browser_ui_prefs.h"
106 #include "chrome/browser/ui/browser_window.h"
107 #include "chrome/browser/ui/chrome_pages.h"
108 #include "chrome/browser/ui/chrome_select_file_policy.h"
109 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
110 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
111 #include "chrome/browser/ui/fast_unload_controller.h"
112 #include "chrome/browser/ui/find_bar/find_bar.h"
113 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
114 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
115 #include "chrome/browser/ui/global_error/global_error.h"
116 #include "chrome/browser/ui/global_error/global_error_service.h"
117 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
118 #include "chrome/browser/ui/location_bar/location_bar.h"
119 #include "chrome/browser/ui/media_utils.h"
120 #include "chrome/browser/ui/search/search_delegate.h"
121 #include "chrome/browser/ui/search/search_model.h"
122 #include "chrome/browser/ui/search/search_tab_helper.h"
123 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
124 #include "chrome/browser/ui/settings_window_manager.h"
125 #include "chrome/browser/ui/singleton_tabs.h"
126 #include "chrome/browser/ui/status_bubble.h"
127 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
128 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
129 #include "chrome/browser/ui/tab_dialogs.h"
130 #include "chrome/browser/ui/tab_helpers.h"
131 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
132 #include "chrome/browser/ui/tabs/tab_menu_model.h"
133 #include "chrome/browser/ui/tabs/tab_strip_model.h"
134 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
135 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
136 #include "chrome/browser/ui/unload_controller.h"
137 #include "chrome/browser/ui/validation_message_bubble.h"
138 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
139 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
140 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
141 #include "chrome/browser/ui/window_sizer/window_sizer.h"
142 #include "chrome/browser/upgrade_detector.h"
143 #include "chrome/browser/web_applications/web_app.h"
144 #include "chrome/common/chrome_constants.h"
145 #include "chrome/common/chrome_switches.h"
146 #include "chrome/common/custom_handlers/protocol_handler.h"
147 #include "chrome/common/pref_names.h"
148 #include "chrome/common/profiling.h"
149 #include "chrome/common/search_types.h"
150 #include "chrome/common/url_constants.h"
151 #include "chrome/grit/chromium_strings.h"
152 #include "chrome/grit/generated_resources.h"
153 #include "chrome/grit/locale_settings.h"
154 #include "components/app_modal/javascript_dialog_manager.h"
155 #include "components/bookmarks/browser/bookmark_model.h"
156 #include "components/bookmarks/browser/bookmark_utils.h"
157 #include "components/content_settings/core/browser/host_content_settings_map.h"
158 #include "components/history/core/browser/top_sites.h"
159 #include "components/infobars/core/simple_alert_infobar_delegate.h"
160 #include "components/search/search.h"
161 #include "components/sessions/session_types.h"
162 #include "components/startup_metric_utils/startup_metric_utils.h"
163 #include "components/translate/core/browser/language_state.h"
164 #include "components/ui/zoom/zoom_controller.h"
165 #include "components/web_modal/popup_manager.h"
166 #include "components/web_modal/web_contents_modal_dialog_manager.h"
167 #include "content/public/browser/devtools_agent_host.h"
168 #include "content/public/browser/download_item.h"
169 #include "content/public/browser/download_manager.h"
170 #include "content/public/browser/interstitial_page.h"
171 #include "content/public/browser/invalidate_type.h"
172 #include "content/public/browser/navigation_controller.h"
173 #include "content/public/browser/navigation_entry.h"
174 #include "content/public/browser/notification_details.h"
175 #include "content/public/browser/notification_service.h"
176 #include "content/public/browser/plugin_service.h"
177 #include "content/public/browser/render_process_host.h"
178 #include "content/public/browser/render_view_host.h"
179 #include "content/public/browser/render_widget_host_view.h"
180 #include "content/public/browser/site_instance.h"
181 #include "content/public/browser/user_metrics.h"
182 #include "content/public/browser/web_contents.h"
183 #include "content/public/common/content_switches.h"
184 #include "content/public/common/page_zoom.h"
185 #include "content/public/common/renderer_preferences.h"
186 #include "content/public/common/webplugininfo.h"
187 #include "extensions/browser/extension_prefs.h"
188 #include "extensions/browser/extension_registry.h"
189 #include "extensions/browser/extension_system.h"
190 #include "extensions/common/constants.h"
191 #include "extensions/common/extension.h"
192 #include "extensions/common/manifest_handlers/background_info.h"
193 #include "net/base/filename_util.h"
194 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
195 #include "net/cookies/cookie_monster.h"
196 #include "net/url_request/url_request_context.h"
197 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
198 #include "ui/base/l10n/l10n_util.h"
199 #include "ui/base/window_open_disposition.h"
200 #include "ui/gfx/geometry/point.h"
201 #include "ui/shell_dialogs/selected_file_info.h"
203 #if defined(OS_WIN)
204 #include "base/win/metro.h"
205 #include "chrome/browser/ssl/ssl_error_info.h"
206 #include "chrome/browser/task_manager/task_manager.h"
207 #include "chrome/browser/ui/view_ids.h"
208 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
209 #include "components/browser_watcher/exit_funnel_win.h"
210 #include "ui/base/touch/touch_device.h"
211 #include "ui/base/win/shell.h"
212 #endif // OS_WIN
214 #if defined(OS_CHROMEOS)
215 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
216 #endif
218 #if defined(USE_ASH)
219 #include "ash/ash_switches.h"
220 #endif
222 using base::TimeDelta;
223 using base::UserMetricsAction;
224 using content::NativeWebKeyboardEvent;
225 using content::NavigationController;
226 using content::NavigationEntry;
227 using content::OpenURLParams;
228 using content::PluginService;
229 using content::Referrer;
230 using content::RenderWidgetHostView;
231 using content::SiteInstance;
232 using content::WebContents;
233 using extensions::Extension;
234 using ui::WebDialogDelegate;
235 using web_modal::WebContentsModalDialogManager;
236 using blink::WebWindowFeatures;
238 ///////////////////////////////////////////////////////////////////////////////
240 namespace {
242 // How long we wait before updating the browser chrome while loading a page.
243 const int kUIUpdateCoalescingTimeMS = 200;
245 BrowserWindow* CreateBrowserWindow(Browser* browser) {
246 return BrowserWindow::CreateBrowserWindow(browser);
249 // Is the fast tab unload experiment enabled?
250 bool IsFastTabUnloadEnabled() {
251 return base::CommandLine::ForCurrentProcess()->HasSwitch(
252 switches::kEnableFastUnload);
255 bool IsWebAppFrameEnabled() {
256 return base::CommandLine::ForCurrentProcess()->HasSwitch(
257 switches::kEnableWebAppFrame);
260 } // namespace
262 ////////////////////////////////////////////////////////////////////////////////
263 // Browser, CreateParams:
265 Browser::CreateParams::CreateParams(Profile* profile,
266 chrome::HostDesktopType host_desktop_type)
267 : type(TYPE_TABBED),
268 profile(profile),
269 host_desktop_type(host_desktop_type),
270 trusted_source(false),
271 initial_show_state(ui::SHOW_STATE_DEFAULT),
272 is_session_restore(false),
273 window(NULL) {
276 Browser::CreateParams::CreateParams(Type type,
277 Profile* profile,
278 chrome::HostDesktopType host_desktop_type)
279 : type(type),
280 profile(profile),
281 host_desktop_type(host_desktop_type),
282 trusted_source(false),
283 initial_show_state(ui::SHOW_STATE_DEFAULT),
284 is_session_restore(false),
285 window(NULL) {
288 // static
289 Browser::CreateParams Browser::CreateParams::CreateForApp(
290 const std::string& app_name,
291 bool trusted_source,
292 const gfx::Rect& window_bounds,
293 Profile* profile,
294 chrome::HostDesktopType host_desktop_type) {
295 DCHECK(!app_name.empty());
297 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
298 params.app_name = app_name;
299 params.trusted_source = trusted_source;
300 params.initial_bounds = window_bounds;
302 return params;
305 // static
306 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
307 Profile* profile,
308 chrome::HostDesktopType host_desktop_type) {
309 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
310 params.app_name = DevToolsWindow::kDevToolsApp;
311 params.trusted_source = true;
312 return params;
315 ////////////////////////////////////////////////////////////////////////////////
316 // Browser, InterstitialObserver:
318 class Browser::InterstitialObserver : public content::WebContentsObserver {
319 public:
320 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
321 : WebContentsObserver(web_contents),
322 browser_(browser) {
325 void DidAttachInterstitialPage() override {
326 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
329 void DidDetachInterstitialPage() override {
330 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
333 private:
334 Browser* browser_;
336 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
339 ///////////////////////////////////////////////////////////////////////////////
340 // Browser, Constructors, Creation, Showing:
342 Browser::Browser(const CreateParams& params)
343 : extension_registry_observer_(this),
344 type_(params.type),
345 profile_(params.profile),
346 window_(NULL),
347 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
348 tab_strip_model_(
349 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
350 app_name_(params.app_name),
351 is_trusted_source_(params.trusted_source),
352 cancel_download_confirmation_state_(NOT_PROMPTED),
353 override_bounds_(params.initial_bounds),
354 initial_show_state_(params.initial_show_state),
355 is_session_restore_(params.is_session_restore),
356 host_desktop_type_(
357 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
358 content_setting_bubble_model_delegate_(
359 new BrowserContentSettingBubbleModelDelegate(this)),
360 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
361 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
362 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
363 bookmark_bar_state_(BookmarkBar::HIDDEN),
364 command_controller_(new chrome::BrowserCommandController(this)),
365 window_has_shown_(false),
366 chrome_updater_factory_(this),
367 weak_factory_(this) {
368 // If this causes a crash then a window is being opened using a profile type
369 // that is disallowed by policy. The crash prevents the disabled window type
370 // from opening at all, but the path that triggered it should be fixed.
371 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
372 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
373 << "Only off the record browser may be opened in guest mode";
375 // TODO(jeremy): Move to initializer list once flag is removed.
376 if (IsFastTabUnloadEnabled())
377 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
378 else
379 unload_controller_.reset(new chrome::UnloadController(this));
381 tab_strip_model_->AddObserver(this);
383 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
384 search_model_.reset(new SearchModel());
385 search_delegate_.reset(new SearchDelegate(search_model_.get()));
387 extension_registry_observer_.Add(
388 extensions::ExtensionRegistry::Get(profile_));
389 registrar_.Add(this,
390 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
391 content::NotificationService::AllSources());
392 #if defined(ENABLE_THEMES)
393 registrar_.Add(
394 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
395 content::Source<ThemeService>(
396 ThemeServiceFactory::GetForProfile(profile_)));
397 #endif
398 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
399 content::NotificationService::AllSources());
401 profile_pref_registrar_.Init(profile_->GetPrefs());
402 profile_pref_registrar_.Add(
403 prefs::kDevToolsDisabled,
404 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
405 profile_pref_registrar_.Add(
406 bookmarks::prefs::kShowBookmarkBar,
407 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
408 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
410 BrowserList::AddBrowser(this);
412 // NOTE: These prefs all need to be explicitly destroyed in the destructor
413 // or you'll get a nasty surprise when you run the incognito tests.
414 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
415 profile_->GetPrefs());
417 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
418 instant_controller_.reset(new BrowserInstantController(this));
420 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
422 ProfileMetrics::LogProfileLaunch(profile_);
424 window_ = params.window ? params.window : CreateBrowserWindow(this);
426 // Create the extension window controller before sending notifications.
427 extension_window_controller_.reset(
428 new BrowserExtensionWindowController(this));
430 SessionService* session_service =
431 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
432 if (session_service)
433 session_service->WindowOpened(this);
435 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
436 // replace uses of this with BL's notifications.
437 content::NotificationService::current()->Notify(
438 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
439 content::Source<Browser>(this),
440 content::NotificationService::NoDetails());
442 // TODO(beng): move to ChromeBrowserMain:
443 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
444 #if defined(OS_WIN)
445 // Notify PDM that this is a first run.
446 ImportAutofillDataWin(
447 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
448 #endif // defined(OS_WIN)
451 exclusive_access_manager_.reset(
452 new ExclusiveAccessManager(window_->GetExclusiveAccessContext()));
454 // Must be initialized after window_.
455 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
456 // without a modal dialog host, so that value may be null.
457 popup_manager_.reset(new web_modal::PopupManager(
458 GetWebContentsModalDialogHost()));
461 Browser::~Browser() {
462 // Stop observing notifications before continuing with destruction. Profile
463 // destruction will unload extensions and reentrant calls to Browser:: should
464 // be avoided while it is being torn down.
465 registrar_.RemoveAll();
466 extension_registry_observer_.RemoveAll();
468 // The tab strip should not have any tabs at this point.
469 DCHECK(tab_strip_model_->empty());
470 tab_strip_model_->RemoveObserver(this);
472 // Destroy the BrowserCommandController before removing the browser, so that
473 // it doesn't act on any notifications that are sent as a result of removing
474 // the browser.
475 command_controller_.reset();
476 BrowserList::RemoveBrowser(this);
478 SessionService* session_service =
479 SessionServiceFactory::GetForProfile(profile_);
480 if (session_service)
481 session_service->WindowClosed(session_id_);
483 TabRestoreService* tab_restore_service =
484 TabRestoreServiceFactory::GetForProfile(profile());
485 if (tab_restore_service)
486 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
488 #if !defined(OS_MACOSX)
489 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
490 // We're the last browser window with this profile. We need to nuke the
491 // TabRestoreService, which will start the shutdown of the
492 // NavigationControllers and allow for proper shutdown. If we don't do this
493 // chrome won't shutdown cleanly, and may end up crashing when some
494 // thread tries to use the IO thread (or another thread) that is no longer
495 // valid.
496 // This isn't a valid assumption for Mac OS, as it stays running after
497 // the last browser has closed. The Mac equivalent is in its app
498 // controller.
499 TabRestoreServiceFactory::ResetForProfile(profile_);
501 #endif
503 profile_pref_registrar_.RemoveAll();
505 encoding_auto_detect_.Destroy();
507 // Destroy BrowserExtensionWindowController before the incognito profile
508 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
509 extension_window_controller_.reset();
511 // Destroy BrowserInstantController before the incongnito profile is destroyed
512 // because the InstantController destructor depends on this profile.
513 instant_controller_.reset();
515 if (profile_->IsOffTheRecord() &&
516 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
517 if (profile_->IsGuestSession()) {
518 // ChromeOS handles guest data independently.
519 #if !defined(OS_CHROMEOS)
520 // Clear all browsing data once a Guest Session completes. The Guest
521 // profile has BrowserContextKeyedServices that the Incognito profile
522 // doesn't, so the ProfileDestroyer can't delete it properly.
523 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
524 BrowsingDataRemover* data_remover =
525 BrowsingDataRemover::CreateForUnboundedRange(profile_);
526 data_remover->Remove(BrowsingDataRemover::REMOVE_ALL,
527 BrowsingDataHelper::ALL);
528 // BrowsingDataRemover deletes itself.
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 FindBarController* Browser::GetFindBarController() {
554 if (!find_bar_controller_.get()) {
555 FindBar* find_bar = window_->CreateFindBar();
556 find_bar_controller_.reset(new FindBarController(find_bar));
557 find_bar->SetFindBarController(find_bar_controller_.get());
558 find_bar_controller_->ChangeWebContents(
559 tab_strip_model_->GetActiveWebContents());
560 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
562 return find_bar_controller_.get();
565 bool Browser::HasFindBarController() const {
566 return find_bar_controller_.get() != NULL;
569 bool Browser::is_app() const {
570 return !app_name_.empty();
573 bool Browser::is_devtools() const {
574 return app_name_ == DevToolsWindow::kDevToolsApp;
577 ///////////////////////////////////////////////////////////////////////////////
578 // Browser, State Storage and Retrieval for UI:
580 gfx::Image Browser::GetCurrentPageIcon() const {
581 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
582 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
583 // window during the window's creation (before tabs have been added).
584 FaviconTabHelper* favicon_tab_helper =
585 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
586 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
589 base::string16 Browser::GetWindowTitleForCurrentTab() const {
590 WebContents* contents = tab_strip_model_->GetActiveWebContents();
591 base::string16 title;
593 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
594 // window during the window's creation (before tabs have been added).
595 if (contents) {
596 // The web app frame uses the host instead of the title.
597 if (ShouldUseWebAppFrame())
598 return base::UTF8ToUTF16(contents->GetURL().host());
600 title = contents->GetTitle();
601 FormatTitleForDisplay(&title);
603 if (title.empty())
604 title = CoreTabHelper::GetDefaultTitle();
606 #if defined(OS_MACOSX)
607 // On Mac, we don't want to suffix the page title with
608 // the application name.
609 return title;
610 #elif defined(USE_ASH)
611 // On Ash, we don't want to suffix the page title with the application name,
612 // but on Windows, where USE_ASH can also be true, we still want the prefix
613 // on desktop.
614 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
615 return title;
616 #endif
617 // Don't append the app name to window titles on app frames and app popups
618 return is_app() ?
619 title :
620 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
623 // static
624 void Browser::FormatTitleForDisplay(base::string16* title) {
625 size_t current_index = 0;
626 size_t match_index;
627 while ((match_index = title->find(L'\n', current_index)) !=
628 base::string16::npos) {
629 title->replace(match_index, 1, base::string16());
630 current_index = match_index;
634 ///////////////////////////////////////////////////////////////////////////////
635 // Browser, OnBeforeUnload handling:
637 bool Browser::ShouldCloseWindow() {
638 if (!CanCloseWithInProgressDownloads())
639 return false;
641 if (IsFastTabUnloadEnabled())
642 return fast_unload_controller_->ShouldCloseWindow();
643 return unload_controller_->ShouldCloseWindow();
646 bool Browser::CallBeforeUnloadHandlers(
647 const base::Callback<void(bool)>& on_close_confirmed) {
648 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
649 if (IsFastTabUnloadEnabled()) {
650 return fast_unload_controller_->CallBeforeUnloadHandlers(
651 on_close_confirmed);
653 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
656 void Browser::ResetBeforeUnloadHandlers() {
657 cancel_download_confirmation_state_ = NOT_PROMPTED;
658 if (IsFastTabUnloadEnabled())
659 fast_unload_controller_->ResetBeforeUnloadHandlers();
660 else
661 unload_controller_->ResetBeforeUnloadHandlers();
664 bool Browser::HasCompletedUnloadProcessing() const {
665 DCHECK(IsFastTabUnloadEnabled());
666 return fast_unload_controller_->HasCompletedUnloadProcessing();
669 bool Browser::IsAttemptingToCloseBrowser() const {
670 if (IsFastTabUnloadEnabled())
671 return fast_unload_controller_->is_attempting_to_close_browser();
672 return unload_controller_->is_attempting_to_close_browser();
675 void Browser::OnWindowClosing() {
676 if (!ShouldCloseWindow())
677 return;
679 // Application should shutdown on last window close if the user is explicitly
680 // trying to quit, or if there is nothing keeping the browser alive (such as
681 // AppController on the Mac, or BackgroundContentsService for background
682 // pages).
683 bool should_quit_if_last_browser =
684 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
686 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this)) {
687 #if defined(OS_WIN)
688 browser_watcher::ExitFunnel::RecordSingleEvent(
689 chrome::kBrowserExitCodesRegistryPath, L"LastWindowClose");
690 #endif
691 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
694 // Don't use GetForProfileIfExisting here, we want to force creation of the
695 // session service so that user can restore what was open.
696 SessionService* session_service =
697 SessionServiceFactory::GetForProfile(profile());
698 if (session_service)
699 session_service->WindowClosing(session_id());
701 TabRestoreService* tab_restore_service =
702 TabRestoreServiceFactory::GetForProfile(profile());
704 #if defined(USE_AURA)
705 if (tab_restore_service && is_app() && !is_devtools())
706 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
707 #endif
709 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
710 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
712 // TODO(sky): convert session/tab restore to use notification.
713 content::NotificationService::current()->Notify(
714 chrome::NOTIFICATION_BROWSER_CLOSING,
715 content::Source<Browser>(this),
716 content::NotificationService::NoDetails());
718 if (!IsFastTabUnloadEnabled())
719 tab_strip_model_->CloseAllTabs();
722 ////////////////////////////////////////////////////////////////////////////////
723 // In-progress download termination handling:
725 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
726 if (cancel_downloads) {
727 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
728 chrome::CloseWindow(this);
729 return;
732 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
733 // close again we'll show the warning again.
734 cancel_download_confirmation_state_ = NOT_PROMPTED;
736 // Show the download page so the user can figure-out what downloads are still
737 // in-progress.
738 chrome::ShowDownloads(this);
740 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
741 // prompt every time any tab is closed. http://crbug.com/305516
742 if (IsFastTabUnloadEnabled())
743 fast_unload_controller_->CancelWindowClose();
744 else
745 unload_controller_->CancelWindowClose();
748 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
749 int* num_downloads_blocking) const {
750 DCHECK(num_downloads_blocking);
751 *num_downloads_blocking = 0;
753 // If we're not running a full browser process with a profile manager
754 // (testing), it's ok to close the browser.
755 if (!g_browser_process->profile_manager())
756 return DOWNLOAD_CLOSE_OK;
758 int total_download_count =
759 DownloadService::NonMaliciousDownloadCountAllProfiles();
760 if (total_download_count == 0)
761 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
763 // Figure out how many windows are open total, and associated with this
764 // profile, that are relevant for the ok-to-close decision.
765 int profile_window_count = 0;
766 int total_window_count = 0;
767 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
768 // Don't count this browser window or any other in the process of closing.
769 Browser* const browser = *it;
770 // Window closing may be delayed, and windows that are in the process of
771 // closing don't count against our totals.
772 if (browser == this || browser->IsAttemptingToCloseBrowser())
773 continue;
775 if (it->profile() == profile())
776 profile_window_count++;
777 total_window_count++;
780 // If there aren't any other windows, we're at browser shutdown,
781 // which would cancel all current downloads.
782 if (total_window_count == 0) {
783 *num_downloads_blocking = total_download_count;
784 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
787 // If there aren't any other windows on our profile, and we're an incognito
788 // profile, and there are downloads associated with that profile,
789 // those downloads would be cancelled by our window (-> profile) close.
790 DownloadService* download_service =
791 DownloadServiceFactory::GetForBrowserContext(profile());
792 if ((profile_window_count == 0) &&
793 (download_service->NonMaliciousDownloadCount() > 0) &&
794 profile()->IsOffTheRecord()) {
795 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
796 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
799 // Those are the only conditions under which we will block shutdown.
800 return DOWNLOAD_CLOSE_OK;
803 ////////////////////////////////////////////////////////////////////////////////
804 // Browser, Tab adding/showing functions:
806 void Browser::WindowFullscreenStateChanged() {
807 exclusive_access_manager_->fullscreen_controller()
808 ->WindowFullscreenStateChanged();
809 command_controller_->FullscreenStateChanged();
810 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
813 ///////////////////////////////////////////////////////////////////////////////
814 // Browser, Assorted browser commands:
816 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
817 exclusive_access_manager_->fullscreen_controller()
818 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
821 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
822 return SupportsWindowFeatureImpl(feature, true);
825 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
826 return SupportsWindowFeatureImpl(feature, false);
829 void Browser::ToggleEncodingAutoDetect() {
830 content::RecordAction(UserMetricsAction("AutoDetectChange"));
831 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
832 // If "auto detect" is turned on, then any current override encoding
833 // is cleared. This also implicitly performs a reload.
834 // OTOH, if "auto detect" is turned off, we don't change the currently
835 // active encoding.
836 if (encoding_auto_detect_.GetValue()) {
837 WebContents* contents = tab_strip_model_->GetActiveWebContents();
838 if (contents)
839 contents->ResetOverrideEncoding();
843 void Browser::OverrideEncoding(int encoding_id) {
844 content::RecordAction(UserMetricsAction("OverrideEncoding"));
845 const std::string selected_encoding =
846 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
847 WebContents* contents = tab_strip_model_->GetActiveWebContents();
848 if (!selected_encoding.empty() && contents)
849 contents->SetOverrideEncoding(selected_encoding);
850 // Update the list of recently selected encodings.
851 std::string new_selected_encoding_list;
852 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
853 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
854 encoding_id,
855 &new_selected_encoding_list)) {
856 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
857 new_selected_encoding_list);
861 void Browser::OpenFile() {
862 content::RecordAction(UserMetricsAction("OpenFile"));
863 select_file_dialog_ = ui::SelectFileDialog::Create(
864 this, new ChromeSelectFilePolicy(
865 tab_strip_model_->GetActiveWebContents()));
867 const base::FilePath directory = profile_->last_selected_directory();
869 // TODO(beng): figure out how to juggle this.
870 gfx::NativeWindow parent_window = window_->GetNativeWindow();
871 ui::SelectFileDialog::FileTypeInfo file_types;
872 file_types.support_drive = true;
873 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
874 base::string16(),
875 directory,
876 &file_types,
878 base::FilePath::StringType(),
879 parent_window,
880 NULL);
883 void Browser::UpdateDownloadShelfVisibility(bool visible) {
884 if (GetStatusBubble())
885 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
888 ///////////////////////////////////////////////////////////////////////////////
890 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
891 ui::PageTransition transition,
892 bool user_initiated) {
893 tab_strip_model_->TabNavigating(contents, transition);
895 bool contents_is_selected =
896 contents == tab_strip_model_->GetActiveWebContents();
897 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
898 // Forcibly reset the location bar if the url is going to change in the
899 // current tab, since otherwise it won't discard any ongoing user edits,
900 // since it doesn't realize this is a user-initiated action.
901 window()->GetLocationBar()->Revert();
904 if (GetStatusBubble())
905 GetStatusBubble()->Hide();
907 // Update the location bar. This is synchronous. We specifically don't
908 // update the load state since the load hasn't started yet and updating it
909 // will put it out of sync with the actual state like whether we're
910 // displaying a favicon, which controls the throbber. If we updated it here,
911 // the throbber will show the default favicon for a split second when
912 // navigating away from the new tab page.
913 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
915 if (contents_is_selected)
916 contents->SetInitialFocus();
919 ///////////////////////////////////////////////////////////////////////////////
920 // Browser, PageNavigator implementation:
922 WebContents* Browser::OpenURL(const OpenURLParams& params) {
923 return OpenURLFromTab(NULL, params);
926 ///////////////////////////////////////////////////////////////////////////////
927 // Browser, TabStripModelObserver implementation:
929 void Browser::TabInsertedAt(WebContents* contents,
930 int index,
931 bool foreground) {
932 SetAsDelegate(contents, true);
934 if (popup_manager_)
935 popup_manager_->RegisterWith(contents);
937 SessionTabHelper* session_tab_helper =
938 SessionTabHelper::FromWebContents(contents);
939 session_tab_helper->SetWindowID(session_id());
941 content::NotificationService::current()->Notify(
942 chrome::NOTIFICATION_TAB_PARENTED,
943 content::Source<content::WebContents>(contents),
944 content::NotificationService::NoDetails());
946 SyncHistoryWithTabs(index);
948 // Make sure the loading state is updated correctly, otherwise the throbber
949 // won't start if the page is loading.
950 LoadingStateChanged(contents, true);
952 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
954 SessionService* session_service =
955 SessionServiceFactory::GetForProfile(profile_);
956 if (session_service) {
957 session_service->TabInserted(contents);
958 int new_active_index = tab_strip_model_->active_index();
959 if (index < new_active_index)
960 session_service->SetSelectedTabInWindow(session_id(),
961 new_active_index);
965 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
966 WebContents* contents,
967 int index) {
968 exclusive_access_manager_->OnTabClosing(contents);
969 SessionService* session_service =
970 SessionServiceFactory::GetForProfile(profile_);
971 if (session_service)
972 session_service->TabClosing(contents);
973 content::NotificationService::current()->Notify(
974 chrome::NOTIFICATION_TAB_CLOSING,
975 content::Source<NavigationController>(&contents->GetController()),
976 content::NotificationService::NoDetails());
978 if (popup_manager_)
979 popup_manager_->UnregisterWith(contents);
981 // Sever the WebContents' connection back to us.
982 SetAsDelegate(contents, false);
985 void Browser::TabDetachedAt(WebContents* contents, int index) {
986 // TabDetachedAt is called before TabStripModel has updated the
987 // active index.
988 int old_active_index = tab_strip_model_->active_index();
989 if (index < old_active_index && !tab_strip_model_->closing_all()) {
990 SessionService* session_service =
991 SessionServiceFactory::GetForProfileIfExisting(profile_);
992 if (session_service)
993 session_service->SetSelectedTabInWindow(session_id(),
994 old_active_index - 1);
997 if (popup_manager_)
998 popup_manager_->UnregisterWith(contents);
1000 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1003 void Browser::TabDeactivated(WebContents* contents) {
1004 exclusive_access_manager_->OnTabDeactivated(contents);
1005 search_delegate_->OnTabDeactivated(contents);
1006 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
1008 // Save what the user's currently typing, so it can be restored when we
1009 // switch back to this tab.
1010 window_->GetLocationBar()->SaveStateToContents(contents);
1012 if (instant_controller_)
1013 instant_controller_->TabDeactivated(contents);
1016 void Browser::ActiveTabChanged(WebContents* old_contents,
1017 WebContents* new_contents,
1018 int index,
1019 int reason) {
1020 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1022 // Update the bookmark state, since the BrowserWindow may query it during
1023 // OnActiveTabChanged() below.
1024 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1026 // Let the BrowserWindow do its handling. On e.g. views this changes the
1027 // focused object, which should happen before we update the toolbar below,
1028 // since the omnibox expects the correct element to already be focused when it
1029 // is updated.
1030 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1032 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
1034 // Discarded tabs always get reloaded.
1035 if (tab_strip_model_->IsTabDiscarded(index)) {
1036 LOG(WARNING) << "Reloading discarded tab at " << index;
1037 static int reload_count = 0;
1038 UMA_HISTOGRAM_CUSTOM_COUNTS(
1039 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1040 chrome::Reload(this, CURRENT_TAB);
1043 // If we have any update pending, do it now.
1044 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1045 ProcessPendingUIUpdates();
1047 // Propagate the profile to the location bar.
1048 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1050 if (chrome::IsInstantExtendedAPIEnabled())
1051 search_delegate_->OnTabActivated(new_contents);
1053 // Update reload/stop state.
1054 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1056 // Update commands to reflect current state.
1057 command_controller_->TabStateChanged();
1059 // Reset the status bubble.
1060 StatusBubble* status_bubble = GetStatusBubble();
1061 if (status_bubble) {
1062 status_bubble->Hide();
1064 // Show the loading state (if any).
1065 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1066 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1069 if (HasFindBarController()) {
1070 find_bar_controller_->ChangeWebContents(new_contents);
1071 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1074 // Update sessions. Don't force creation of sessions. If sessions doesn't
1075 // exist, the change will be picked up by sessions when created.
1076 SessionService* session_service =
1077 SessionServiceFactory::GetForProfileIfExisting(profile_);
1078 if (session_service && !tab_strip_model_->closing_all()) {
1079 session_service->SetSelectedTabInWindow(session_id(),
1080 tab_strip_model_->active_index());
1083 // This needs to be called after notifying SearchDelegate.
1084 if (instant_controller_)
1085 instant_controller_->ActiveTabChanged();
1087 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1088 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1091 void Browser::TabMoved(WebContents* contents,
1092 int from_index,
1093 int to_index) {
1094 DCHECK(from_index >= 0 && to_index >= 0);
1095 // Notify the history service.
1096 SyncHistoryWithTabs(std::min(from_index, to_index));
1099 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1100 WebContents* old_contents,
1101 WebContents* new_contents,
1102 int index) {
1103 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1104 exclusive_access_manager_->OnTabClosing(old_contents);
1105 SessionService* session_service =
1106 SessionServiceFactory::GetForProfile(profile_);
1107 if (session_service)
1108 session_service->TabClosing(old_contents);
1109 TabInsertedAt(new_contents,
1110 index,
1111 (index == tab_strip_model_->active_index()));
1113 int entry_count = new_contents->GetController().GetEntryCount();
1114 if (entry_count > 0) {
1115 // Send out notification so that observers are updated appropriately.
1116 new_contents->GetController().NotifyEntryChanged(
1117 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1118 entry_count - 1);
1121 if (session_service) {
1122 // The new_contents may end up with a different navigation stack. Force
1123 // the session service to update itself.
1124 session_service->TabRestored(new_contents,
1125 tab_strip_model_->IsTabPinned(index));
1129 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1130 SessionService* session_service =
1131 SessionServiceFactory::GetForProfileIfExisting(profile());
1132 if (session_service) {
1133 SessionTabHelper* session_tab_helper =
1134 SessionTabHelper::FromWebContents(contents);
1135 session_service->SetPinnedState(session_id(),
1136 session_tab_helper->session_id(),
1137 tab_strip_model_->IsTabPinned(index));
1141 void Browser::TabStripEmpty() {
1142 // Close the frame after we return to the message loop (not immediately,
1143 // otherwise it will destroy this object before the stack has a chance to
1144 // cleanly unwind.)
1145 // Note: This will be called several times if TabStripEmpty is called several
1146 // times. This is because it does not close the window if tabs are
1147 // still present.
1148 base::MessageLoop::current()->PostTask(
1149 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1151 // Instant may have visible WebContents that need to be detached before the
1152 // window system closes.
1153 instant_controller_.reset();
1156 bool Browser::CanOverscrollContent() const {
1157 #if defined(OS_WIN)
1158 // Don't enable overscroll on Windows machines unless they have a touch
1159 // screen as these machines typically don't have a touchpad capable of
1160 // horizontal scrolling. We are purposefully biased towards "no" here,
1161 // so that we don't waste resources capturing screenshots for horizontal
1162 // overscroll navigation unnecessarily.
1163 bool allow_overscroll = ui::IsTouchDevicePresent();
1164 #elif defined(USE_AURA)
1165 bool allow_overscroll = true;
1166 #else
1167 bool allow_overscroll = false;
1168 #endif
1170 if (!allow_overscroll)
1171 return false;
1173 const std::string value =
1174 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1175 switches::kOverscrollHistoryNavigation);
1176 bool overscroll_enabled = value != "0";
1177 if (!overscroll_enabled)
1178 return false;
1179 if (is_app() || is_devtools() || !is_type_tabbed())
1180 return false;
1182 // The detached bookmark bar has appearance of floating above the
1183 // web-contents. This does not play nicely with overscroll navigation
1184 // gestures. So disable overscroll navigation when the bookmark bar is in the
1185 // detached state and the overscroll effect moves the layers.
1186 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1187 return false;
1188 return true;
1191 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1192 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1193 // other pages have committed.
1194 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1195 if (!profile || !source->GetController().GetLastCommittedEntry())
1196 return false;
1197 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1198 return chrome::IsNTPURL(committed_url, profile);
1201 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1202 const NativeWebKeyboardEvent& event,
1203 bool* is_keyboard_shortcut) {
1204 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1205 // TODO(koz): Write a test for this http://crbug.com/100441.
1206 if (event.windowsKeyCode == 27 &&
1207 exclusive_access_manager_->HandleUserPressedEscape()) {
1208 return true;
1210 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1213 void Browser::HandleKeyboardEvent(content::WebContents* source,
1214 const NativeWebKeyboardEvent& event) {
1215 DevToolsWindow* devtools_window =
1216 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1217 bool handled = false;
1218 if (devtools_window)
1219 handled = devtools_window->ForwardKeyboardEvent(event);
1221 if (!handled)
1222 window()->HandleKeyboardEvent(event);
1225 bool Browser::TabsNeedBeforeUnloadFired() {
1226 if (IsFastTabUnloadEnabled())
1227 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1228 return unload_controller_->TabsNeedBeforeUnloadFired();
1231 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1232 const gfx::Rect& anchor_in_root_view,
1233 const base::string16& main_text,
1234 const base::string16& sub_text) {
1235 validation_message_bubble_ =
1236 TabDialogs::FromWebContents(web_contents)
1237 ->ShowValidationMessage(anchor_in_root_view, main_text, sub_text);
1240 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1241 validation_message_bubble_.reset();
1244 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1245 const gfx::Rect& anchor_in_root_view) {
1246 if (!validation_message_bubble_)
1247 return;
1248 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1249 if (rwhv) {
1250 validation_message_bubble_->SetPositionRelativeToAnchor(
1251 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1255 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1256 const blink::WebGestureEvent& event) {
1257 // Disable pinch zooming in undocked dev tools window due to poor UX.
1258 if (app_name() == DevToolsWindow::kDevToolsApp)
1259 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1260 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1261 event.type == blink::WebGestureEvent::GesturePinchEnd;
1263 return false;
1266 bool Browser::CanDragEnter(content::WebContents* source,
1267 const content::DropData& data,
1268 blink::WebDragOperationsMask operations_allowed) {
1269 // Disallow drag-and-drop navigation for Settings windows which do not support
1270 // external navigation.
1271 if ((operations_allowed & blink::WebDragOperationLink) &&
1272 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1273 return false;
1275 return true;
1278 bool Browser::IsMouseLocked() const {
1279 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1282 void Browser::OnWindowDidShow() {
1283 if (window_has_shown_)
1284 return;
1285 window_has_shown_ = true;
1287 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1288 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1289 // Measure the latency from startup till the first browser window becomes
1290 // visible.
1291 static bool is_first_browser_window = true;
1292 if (is_first_browser_window &&
1293 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1294 is_first_browser_window = false;
1295 const base::Time process_creation_time =
1296 base::CurrentProcessInfo::CreationTime();
1298 if (!process_creation_time.is_null()) {
1299 UMA_HISTOGRAM_LONG_TIMES(
1300 "Startup.BrowserWindowDisplay",
1301 base::Time::Now() - process_creation_time);
1304 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1306 // Nothing to do for non-tabbed windows.
1307 if (!is_type_tabbed())
1308 return;
1310 // Show any pending global error bubble.
1311 GlobalErrorService* service =
1312 GlobalErrorServiceFactory::GetForProfile(profile());
1313 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1314 if (error)
1315 error->ShowBubbleView(this);
1318 void Browser::ShowFirstRunBubble() {
1319 window()->GetLocationBar()->ShowFirstRunBubble();
1322 void Browser::ShowDownload(content::DownloadItem* download) {
1323 if (!window())
1324 return;
1326 // If the download occurs in a new tab, and it's not a save page
1327 // download (started before initial navigation completed) close it.
1328 // Avoid calling CloseContents if the tab is not in this browser's tab strip
1329 // model; this can happen if the download was initiated by something internal
1330 // to Chrome, such as by the app list.
1331 WebContents* source = download->GetWebContents();
1332 if (source && source->GetController().IsInitialNavigation() &&
1333 tab_strip_model_->count() > 1 &&
1334 tab_strip_model_->GetIndexOfWebContents(source) !=
1335 TabStripModel::kNoTab &&
1336 !download->IsSavePackageDownload()) {
1337 CloseContents(source);
1340 // Some (app downloads) are not supposed to appear on the shelf.
1341 if (!DownloadItemModel(download).ShouldShowInShelf())
1342 return;
1344 // GetDownloadShelf creates the download shelf if it was not yet created.
1345 window()->GetDownloadShelf()->AddDownload(download);
1348 ///////////////////////////////////////////////////////////////////////////////
1349 // Browser, content::WebContentsDelegate implementation:
1351 WebContents* Browser::OpenURLFromTab(WebContents* source,
1352 const OpenURLParams& params) {
1353 if (is_devtools()) {
1354 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1355 DCHECK(window);
1356 return window->OpenURLFromTab(source, params);
1359 chrome::NavigateParams nav_params(this, params.url, params.transition);
1360 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1361 nav_params.source_contents = source;
1362 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1363 if (params.user_gesture)
1364 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1365 nav_params.user_gesture = params.user_gesture;
1367 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1368 if (source)
1369 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1371 if (popup_blocker_helper) {
1372 if ((params.disposition == NEW_POPUP ||
1373 params.disposition == NEW_FOREGROUND_TAB ||
1374 params.disposition == NEW_BACKGROUND_TAB ||
1375 params.disposition == NEW_WINDOW) &&
1376 !params.user_gesture &&
1377 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1378 switches::kDisablePopupBlocking)) {
1379 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1380 WebWindowFeatures())) {
1381 return NULL;
1386 chrome::Navigate(&nav_params);
1388 return nav_params.target_contents;
1391 void Browser::NavigationStateChanged(WebContents* source,
1392 content::InvalidateTypes changed_flags) {
1393 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1394 // is fixed.
1395 tracked_objects::ScopedTracker tracking_profile1(
1396 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1397 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1398 // Only update the UI when something visible has changed.
1399 if (changed_flags)
1400 ScheduleUIUpdate(source, changed_flags);
1402 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1403 // is fixed.
1404 tracked_objects::ScopedTracker tracking_profile2(
1405 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1406 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1407 // We can synchronously update commands since they will only change once per
1408 // navigation, so we don't have to worry about flickering. We do, however,
1409 // need to update the command state early on load to always present usable
1410 // actions in the face of slow-to-commit pages.
1411 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1412 content::INVALIDATE_TYPE_LOAD))
1413 command_controller_->TabStateChanged();
1416 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1417 // When the current tab's SSL state changes, we need to update the URL
1418 // bar to reflect the new state.
1419 DCHECK(source);
1420 if (tab_strip_model_->GetActiveWebContents() == source)
1421 UpdateToolbar(false);
1424 void Browser::AddNewContents(WebContents* source,
1425 WebContents* new_contents,
1426 WindowOpenDisposition disposition,
1427 const gfx::Rect& initial_rect,
1428 bool user_gesture,
1429 bool* was_blocked) {
1430 chrome::AddWebContents(this, source, new_contents, disposition, initial_rect,
1431 user_gesture, was_blocked);
1434 void Browser::ActivateContents(WebContents* contents) {
1435 tab_strip_model_->ActivateTabAt(
1436 tab_strip_model_->GetIndexOfWebContents(contents), false);
1437 window_->Activate();
1440 void Browser::DeactivateContents(WebContents* contents) {
1441 window_->Deactivate();
1444 void Browser::LoadingStateChanged(WebContents* source,
1445 bool to_different_document) {
1446 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1447 window_->UpdateTitleBar();
1449 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1450 if (source == selected_contents) {
1451 bool is_loading = source->IsLoading() && to_different_document;
1452 command_controller_->LoadingStateChanged(is_loading, false);
1453 if (GetStatusBubble()) {
1454 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1455 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1460 void Browser::CloseContents(WebContents* source) {
1461 bool can_close_contents;
1462 if (IsFastTabUnloadEnabled())
1463 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1464 else
1465 can_close_contents = unload_controller_->CanCloseContents(source);
1467 if (can_close_contents)
1468 chrome::CloseWebContents(this, source, true);
1471 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1472 if (!IsPopupOrPanel(source)) {
1473 NOTREACHED() << "moving invalid browser type";
1474 return;
1476 window_->SetBounds(pos);
1479 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1480 return is_type_popup();
1483 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1484 if (!GetStatusBubble())
1485 return;
1487 if (source == tab_strip_model_->GetActiveWebContents()) {
1488 PrefService* prefs = profile_->GetPrefs();
1489 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1493 void Browser::ContentsMouseEvent(
1494 WebContents* source, const gfx::Point& location, bool motion) {
1495 if (!GetStatusBubble())
1496 return;
1498 if (source == tab_strip_model_->GetActiveWebContents()) {
1499 GetStatusBubble()->MouseMoved(location, !motion);
1500 if (!motion)
1501 GetStatusBubble()->SetURL(GURL(), std::string());
1505 void Browser::ContentsZoomChange(bool zoom_in) {
1506 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1509 void Browser::WebContentsFocused(WebContents* contents) {
1510 window_->WebContentsFocused(contents);
1513 bool Browser::TakeFocus(content::WebContents* source,
1514 bool reverse) {
1515 content::NotificationService::current()->Notify(
1516 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1517 content::Source<Browser>(this),
1518 content::NotificationService::NoDetails());
1519 return false;
1522 gfx::Rect Browser::GetRootWindowResizerRect() const {
1523 return window_->GetRootWindowResizerRect();
1526 void Browser::BeforeUnloadFired(WebContents* web_contents,
1527 bool proceed,
1528 bool* proceed_to_fire_unload) {
1529 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1530 proceed, proceed_to_fire_unload))
1531 return;
1533 if (IsFastTabUnloadEnabled()) {
1534 *proceed_to_fire_unload =
1535 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1536 } else {
1537 *proceed_to_fire_unload =
1538 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1542 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1543 const content::NavigationEntry* entry =
1544 source->GetController().GetActiveEntry();
1545 if (entry) {
1546 GURL url = entry->GetURL();
1547 GURL virtual_url = entry->GetVirtualURL();
1548 if ((url.SchemeIs(content::kChromeUIScheme) &&
1549 url.host() == chrome::kChromeUINewTabHost) ||
1550 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1551 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1552 return true;
1556 return chrome::NavEntryIsInstantNTP(source, entry);
1559 void Browser::SetFocusToLocationBar(bool select_all) {
1560 // Two differences between this and FocusLocationBar():
1561 // (1) This doesn't get recorded in user metrics, since it's called
1562 // internally.
1563 // (2) This checks whether the location bar can be focused, and if not, clears
1564 // the focus. FocusLocationBar() is only reached when the location bar is
1565 // focusable, but this may be reached at other times, e.g. while in
1566 // fullscreen mode, where we need to leave focus in a consistent state.
1567 window_->SetFocusToLocationBar(select_all);
1570 int Browser::GetExtraRenderViewHeight() const {
1571 return window_->GetExtraRenderViewHeight();
1574 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1575 DCHECK(source);
1576 chrome::ViewSource(this, source);
1579 void Browser::ViewSourceForFrame(WebContents* source,
1580 const GURL& frame_url,
1581 const content::PageState& frame_page_state) {
1582 DCHECK(source);
1583 chrome::ViewSource(this, source, frame_url, frame_page_state);
1586 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1587 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1588 source);
1591 bool Browser::ShouldCreateWebContents(
1592 WebContents* web_contents,
1593 int route_id,
1594 int main_frame_route_id,
1595 WindowContainerType window_container_type,
1596 const base::string16& frame_name,
1597 const GURL& target_url,
1598 const std::string& partition_id,
1599 content::SessionStorageNamespace* session_storage_namespace) {
1600 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1601 // If a BackgroundContents is created, suppress the normal WebContents.
1602 return !MaybeCreateBackgroundContents(route_id,
1603 main_frame_route_id,
1604 web_contents,
1605 frame_name,
1606 target_url,
1607 partition_id,
1608 session_storage_namespace);
1611 return true;
1614 void Browser::WebContentsCreated(WebContents* source_contents,
1615 int opener_render_frame_id,
1616 const base::string16& frame_name,
1617 const GURL& target_url,
1618 WebContents* new_contents) {
1619 // Adopt the WebContents now, so all observers are in place, as the network
1620 // requests for its initial navigation will start immediately. The WebContents
1621 // will later be inserted into this browser using Browser::Navigate via
1622 // AddNewContents.
1623 TabHelpers::AttachTabHelpers(new_contents);
1625 // Notify.
1626 RetargetingDetails details;
1627 details.source_web_contents = source_contents;
1628 details.source_render_frame_id = opener_render_frame_id;
1629 details.target_url = target_url;
1630 details.target_web_contents = new_contents;
1631 details.not_yet_in_tabstrip = true;
1632 content::NotificationService::current()->Notify(
1633 chrome::NOTIFICATION_RETARGETING,
1634 content::Source<Profile>(profile_),
1635 content::Details<RetargetingDetails>(&details));
1638 void Browser::RendererUnresponsive(WebContents* source) {
1639 // Ignore hangs if a tab is blocked.
1640 int index = tab_strip_model_->GetIndexOfWebContents(source);
1641 DCHECK_NE(TabStripModel::kNoTab, index);
1642 if (tab_strip_model_->IsTabBlocked(index))
1643 return;
1645 TabDialogs::FromWebContents(source)->ShowHungRendererDialog();
1648 void Browser::RendererResponsive(WebContents* source) {
1649 TabDialogs::FromWebContents(source)->HideHungRendererDialog();
1652 void Browser::WorkerCrashed(WebContents* source) {
1653 SimpleAlertInfoBarDelegate::Create(
1654 InfoBarService::FromWebContents(source),
1655 infobars::InfoBarDelegate::kNoIconID,
1656 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1659 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1660 if (web_contents == tab_strip_model_->GetActiveWebContents())
1661 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1664 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1665 WebContents* source) {
1666 return app_modal::JavaScriptDialogManager::GetInstance();
1669 content::ColorChooser* Browser::OpenColorChooser(
1670 WebContents* web_contents,
1671 SkColor initial_color,
1672 const std::vector<content::ColorSuggestion>& suggestions) {
1673 return chrome::ShowColorChooser(web_contents, initial_color);
1676 void Browser::RunFileChooser(WebContents* web_contents,
1677 const content::FileChooserParams& params) {
1678 FileSelectHelper::RunFileChooser(web_contents, params);
1681 void Browser::EnumerateDirectory(WebContents* web_contents,
1682 int request_id,
1683 const base::FilePath& path) {
1684 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1687 bool Browser::EmbedsFullscreenWidget() const {
1688 return true;
1691 void Browser::EnterFullscreenModeForTab(WebContents* web_contents,
1692 const GURL& origin) {
1693 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1694 web_contents, origin);
1697 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1698 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1699 web_contents);
1702 bool Browser::IsFullscreenForTabOrPending(
1703 const WebContents* web_contents) const {
1704 return exclusive_access_manager_->fullscreen_controller()
1705 ->IsFullscreenForTabOrPending(web_contents);
1708 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1709 const std::string& protocol,
1710 const GURL& url,
1711 bool user_gesture) {
1712 content::BrowserContext* context = web_contents->GetBrowserContext();
1713 if (context->IsOffTheRecord())
1714 return;
1716 ProtocolHandler handler =
1717 ProtocolHandler::CreateProtocolHandler(protocol, url);
1719 ProtocolHandlerRegistry* registry =
1720 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1721 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1722 return;
1724 TabSpecificContentSettings* tab_content_settings =
1725 TabSpecificContentSettings::FromWebContents(web_contents);
1726 if (!user_gesture && window_) {
1727 tab_content_settings->set_pending_protocol_handler(handler);
1728 tab_content_settings->set_previous_protocol_handler(
1729 registry->GetHandlerFor(handler.protocol()));
1730 window_->GetLocationBar()->UpdateContentSettingsIcons();
1731 return;
1734 // Make sure content-setting icon is turned off in case the page does
1735 // ungestured and gestured RPH calls.
1736 if (window_) {
1737 tab_content_settings->ClearPendingProtocolHandler();
1738 window_->GetLocationBar()->UpdateContentSettingsIcons();
1741 PermissionBubbleManager* bubble_manager =
1742 PermissionBubbleManager::FromWebContents(web_contents);
1743 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1744 bubble_manager->AddRequest(
1745 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1746 url, user_gesture));
1747 } else {
1748 RegisterProtocolHandlerInfoBarDelegate::Create(
1749 InfoBarService::FromWebContents(web_contents), registry, handler);
1753 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1754 const std::string& protocol,
1755 const GURL& url,
1756 bool user_gesture) {
1757 // user_gesture will be used in case we decide to have confirmation bubble
1758 // for user while un-registering the handler.
1759 content::BrowserContext* context = web_contents->GetBrowserContext();
1760 if (context->IsOffTheRecord())
1761 return;
1763 ProtocolHandler handler =
1764 ProtocolHandler::CreateProtocolHandler(protocol, url);
1766 ProtocolHandlerRegistry* registry =
1767 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1768 registry->RemoveHandler(handler);
1771 void Browser::UpdatePreferredSize(WebContents* source,
1772 const gfx::Size& pref_size) {
1773 window_->UpdatePreferredSize(source, pref_size);
1776 void Browser::ResizeDueToAutoResize(WebContents* source,
1777 const gfx::Size& new_size) {
1778 window_->ResizeDueToAutoResize(source, new_size);
1781 void Browser::FindReply(WebContents* web_contents,
1782 int request_id,
1783 int number_of_matches,
1784 const gfx::Rect& selection_rect,
1785 int active_match_ordinal,
1786 bool final_update) {
1787 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1788 if (!find_tab_helper)
1789 return;
1791 find_tab_helper->HandleFindReply(request_id,
1792 number_of_matches,
1793 selection_rect,
1794 active_match_ordinal,
1795 final_update);
1798 void Browser::RequestToLockMouse(WebContents* web_contents,
1799 bool user_gesture,
1800 bool last_unlocked_by_target) {
1801 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
1802 web_contents, user_gesture, last_unlocked_by_target);
1805 void Browser::LostMouseLock() {
1806 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
1809 void Browser::RequestMediaAccessPermission(
1810 content::WebContents* web_contents,
1811 const content::MediaStreamRequest& request,
1812 const content::MediaResponseCallback& callback) {
1813 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1816 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1817 const GURL& security_origin,
1818 content::MediaStreamType type) {
1819 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1822 bool Browser::RequestPpapiBrokerPermission(
1823 WebContents* web_contents,
1824 const GURL& url,
1825 const base::FilePath& plugin_path,
1826 const base::Callback<void(bool)>& callback) {
1827 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1828 return true;
1831 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1832 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1833 // would disappear on non-NTP pages, resulting in a bigger size for the new
1834 // render view.
1835 gfx::Size size = web_contents->GetContainerBounds().size();
1836 // Don't change render view size if bookmark bar is currently not detached,
1837 // or there's no pending entry, or navigating to a NTP page.
1838 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1839 return size;
1840 const NavigationEntry* pending_entry =
1841 web_contents->GetController().GetPendingEntry();
1842 if (pending_entry &&
1843 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1844 size.Enlarge(
1845 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1847 return size;
1850 ///////////////////////////////////////////////////////////////////////////////
1851 // Browser, CoreTabHelperDelegate implementation:
1853 void Browser::SwapTabContents(content::WebContents* old_contents,
1854 content::WebContents* new_contents,
1855 bool did_start_load,
1856 bool did_finish_load) {
1857 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1858 DCHECK_NE(TabStripModel::kNoTab, index);
1859 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1862 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1863 return chrome::CanReload(this);
1866 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1867 return chrome::CanSavePage(this);
1870 ///////////////////////////////////////////////////////////////////////////////
1871 // Browser, SearchEngineTabHelperDelegate implementation:
1873 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1874 Profile* profile) {
1875 window()->ConfirmAddSearchProvider(template_url, profile);
1878 ///////////////////////////////////////////////////////////////////////////////
1879 // Browser, SearchTabHelperDelegate implementation:
1881 void Browser::NavigateOnThumbnailClick(const GURL& url,
1882 WindowOpenDisposition disposition,
1883 content::WebContents* source_contents) {
1884 DCHECK(source_contents);
1885 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1886 // gets called to handle clicks in the new tab page (to navigate to most
1887 // visited item URLs) and in the search results page (to navigate to
1888 // privileged destinations (e.g. chrome://URLs)).
1890 // TODO(kmadhusu): Page transitions to privileged destinations should be
1891 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1892 chrome::NavigateParams params(this, url,
1893 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1894 params.referrer = content::Referrer();
1895 params.source_contents = source_contents;
1896 params.disposition = disposition;
1897 params.is_renderer_initiated = false;
1898 params.initiating_profile = profile_;
1899 chrome::Navigate(&params);
1902 void Browser::OnWebContentsInstantSupportDisabled(
1903 const content::WebContents* web_contents) {
1904 DCHECK(web_contents);
1905 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1906 UpdateToolbar(false);
1909 OmniboxView* Browser::GetOmniboxView() {
1910 return window_->GetLocationBar()->GetOmniboxView();
1913 std::set<std::string> Browser::GetOpenUrls() {
1914 scoped_refptr<history::TopSites> top_sites =
1915 TopSitesFactory::GetForProfile(profile_);
1916 if (!top_sites) // NULL for Incognito profiles.
1917 return std::set<std::string>();
1919 std::set<std::string> open_urls;
1920 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1921 return open_urls;
1924 ///////////////////////////////////////////////////////////////////////////////
1925 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1927 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1928 bool blocked) {
1929 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1930 if (index == TabStripModel::kNoTab) {
1931 NOTREACHED();
1932 return;
1934 tab_strip_model_->SetTabBlocked(index, blocked);
1935 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1936 web_contents->Focus();
1939 web_modal::WebContentsModalDialogHost*
1940 Browser::GetWebContentsModalDialogHost() {
1941 return window_->GetWebContentsModalDialogHost();
1944 ///////////////////////////////////////////////////////////////////////////////
1945 // Browser, BookmarkTabHelperDelegate implementation:
1947 void Browser::URLStarredChanged(content::WebContents* web_contents,
1948 bool starred) {
1949 if (web_contents == tab_strip_model_->GetActiveWebContents())
1950 window_->SetStarredState(starred);
1953 ///////////////////////////////////////////////////////////////////////////////
1954 // Browser, ZoomObserver implementation:
1956 void Browser::OnZoomChanged(
1957 const ui_zoom::ZoomController::ZoomChangedEventData& data) {
1958 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1959 window_->ZoomChangedForActiveTab(data.can_show_bubble);
1960 // Change the zoom commands state based on the zoom state
1961 command_controller_->ZoomStateChanged();
1965 ///////////////////////////////////////////////////////////////////////////////
1966 // Browser, ui::SelectFileDialog::Listener implementation:
1968 void Browser::FileSelected(const base::FilePath& path, int index,
1969 void* params) {
1970 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1973 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1974 int index,
1975 void* params) {
1976 profile_->set_last_selected_directory(file_info.file_path.DirName());
1978 GURL url = net::FilePathToFileURL(file_info.local_path);
1980 #if defined(OS_CHROMEOS)
1981 const GURL external_url =
1982 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
1983 if (!external_url.is_empty())
1984 url = external_url;
1985 #endif
1987 if (url.is_empty())
1988 return;
1990 OpenURL(OpenURLParams(
1991 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
1994 ///////////////////////////////////////////////////////////////////////////////
1995 // Browser, content::NotificationObserver implementation:
1997 void Browser::Observe(int type,
1998 const content::NotificationSource& source,
1999 const content::NotificationDetails& details) {
2000 switch (type) {
2001 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2002 Profile* profile = content::Source<Profile>(source).ptr();
2003 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
2004 window()->GetLocationBar()->UpdatePageActions();
2005 break;
2008 #if defined(ENABLE_THEMES)
2009 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2010 window()->UserChangedTheme();
2011 break;
2012 #endif
2014 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2015 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2016 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2017 LocationBar* location_bar = window()->GetLocationBar();
2018 if (location_bar)
2019 location_bar->UpdateContentSettingsIcons();
2021 break;
2024 default:
2025 NOTREACHED() << "Got a notification we didn't register for.";
2029 #if defined(ENABLE_EXTENSIONS)
2030 ///////////////////////////////////////////////////////////////////////////////
2031 // Browser, extensions::ExtensionRegistryObserver implementation:
2033 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
2034 const extensions::Extension* extension,
2035 extensions::UninstallReason reason) {
2036 // During window creation on Windows we may end up calling into
2037 // SHAppBarMessage, which internally spawns a nested message loop.This
2038 // makes it possible for us to end up here before window creation has
2039 // completed, at which point window_ is NULL. See 94752 for details.
2041 if (window() && window()->GetLocationBar())
2042 window()->GetLocationBar()->UpdatePageActions();
2045 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2046 const extensions::Extension* extension) {
2047 command_controller_->ExtensionStateChanged();
2050 void Browser::OnExtensionUnloaded(
2051 content::BrowserContext* browser_context,
2052 const extensions::Extension* extension,
2053 extensions::UnloadedExtensionInfo::Reason reason) {
2054 command_controller_->ExtensionStateChanged();
2055 if (window()->GetLocationBar())
2056 window()->GetLocationBar()->UpdatePageActions();
2058 // Close any tabs from the unloaded extension, unless it's terminated,
2059 // in which case let the sad tabs remain.
2060 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2061 // Iterate backwards as we may remove items while iterating.
2062 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2063 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2064 // Two cases are handled here:
2066 // - The scheme check is for when an extension page is loaded in a
2067 // tab, e.g. chrome-extension://id/page.html.
2068 // - The extension_app check is for apps, which can have non-extension
2069 // schemes, e.g. https://mail.google.com if you have the Gmail app
2070 // installed.
2071 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2072 web_contents->GetURL().host() == extension->id()) ||
2073 (extensions::TabHelper::FromWebContents(web_contents)
2074 ->extension_app() == extension)) {
2075 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2080 #endif // defined(ENABLE_EXTENSIONS)
2082 ///////////////////////////////////////////////////////////////////////////////
2083 // Browser, translate::ContentTranslateDriver::Observer implementation:
2085 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2086 DCHECK(source);
2087 if (tab_strip_model_->GetActiveWebContents() == source) {
2088 window_->SetTranslateIconToggled(
2089 ChromeTranslateClient::FromWebContents(
2090 source)->GetLanguageState().IsPageTranslated());
2094 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2095 DCHECK(source);
2096 if (tab_strip_model_->GetActiveWebContents() == source)
2097 UpdateToolbar(false);
2100 ///////////////////////////////////////////////////////////////////////////////
2101 // Browser, Command and state updating (private):
2103 void Browser::OnDevToolsDisabledChanged() {
2104 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2105 content::DevToolsAgentHost::DetachAllClients();
2108 ///////////////////////////////////////////////////////////////////////////////
2109 // Browser, UI update coalescing and handling (private):
2111 void Browser::UpdateToolbar(bool should_restore_state) {
2112 window_->UpdateToolbar(should_restore_state ?
2113 tab_strip_model_->GetActiveWebContents() : NULL);
2116 void Browser::ScheduleUIUpdate(WebContents* source,
2117 unsigned changed_flags) {
2118 DCHECK(source);
2119 int index = tab_strip_model_->GetIndexOfWebContents(source);
2120 DCHECK_NE(TabStripModel::kNoTab, index);
2122 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2123 // is fixed.
2124 tracked_objects::ScopedTracker tracking_profile1(
2125 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2126 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2127 // Do some synchronous updates.
2128 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2129 if (source == tab_strip_model_->GetActiveWebContents()) {
2130 // Only update the URL for the current tab. Note that we do not update
2131 // the navigation commands since those would have already been updated
2132 // synchronously by NavigationStateChanged.
2133 UpdateToolbar(false);
2134 } else {
2135 // Clear the saved tab state for the tab that navigated, so that we don't
2136 // restore any user text after the old URL has been invalidated (e.g.,
2137 // after a new navigation commits in that tab while unfocused).
2138 window_->ResetToolbarTabState(source);
2140 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2143 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2144 // is fixed.
2145 tracked_objects::ScopedTracker tracking_profile2(
2146 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2147 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2148 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2149 // Update the loading state synchronously. This is so the throbber will
2150 // immediately start/stop, which gives a more snappy feel. We want to do
2151 // this for any tab so they start & stop quickly.
2152 tab_strip_model_->UpdateWebContentsStateAt(
2153 tab_strip_model_->GetIndexOfWebContents(source),
2154 TabStripModelObserver::LOADING_ONLY);
2155 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2156 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2157 // changed_flags.
2160 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2161 // To correctly calculate whether the title changed while not loading
2162 // we need to process the update synchronously. This state only matters for
2163 // the TabStripModel, so we notify the TabStripModel now and notify others
2164 // asynchronously.
2165 tab_strip_model_->UpdateWebContentsStateAt(
2166 tab_strip_model_->GetIndexOfWebContents(source),
2167 TabStripModelObserver::TITLE_NOT_LOADING);
2170 // If the only updates were synchronously handled above, we're done.
2171 if (changed_flags == 0)
2172 return;
2174 // Save the dirty bits.
2175 scheduled_updates_[source] |= changed_flags;
2177 if (!chrome_updater_factory_.HasWeakPtrs()) {
2178 // No task currently scheduled, start another.
2179 base::MessageLoop::current()->PostDelayedTask(
2180 FROM_HERE,
2181 base::Bind(&Browser::ProcessPendingUIUpdates,
2182 chrome_updater_factory_.GetWeakPtr()),
2183 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2187 void Browser::ProcessPendingUIUpdates() {
2188 #ifndef NDEBUG
2189 // Validate that all tabs we have pending updates for exist. This is scary
2190 // because the pending list must be kept in sync with any detached or
2191 // deleted tabs.
2192 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2193 i != scheduled_updates_.end(); ++i) {
2194 bool found = false;
2195 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2196 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2197 found = true;
2198 break;
2201 DCHECK(found);
2203 #endif
2205 chrome_updater_factory_.InvalidateWeakPtrs();
2207 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2208 // is fixed.
2209 tracked_objects::ScopedTracker tracking_profile1(
2210 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2211 "467185 Browser::ProcessPendingUIUpdates1"));
2213 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2214 i != scheduled_updates_.end(); ++i) {
2215 // Do not dereference |contents|, it may be out-of-date!
2216 const WebContents* contents = i->first;
2217 unsigned flags = i->second;
2219 if (contents == tab_strip_model_->GetActiveWebContents()) {
2220 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2221 // is fixed.
2222 tracked_objects::ScopedTracker tracking_profile2(
2223 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2224 "467185 Browser::ProcessPendingUIUpdates2"));
2226 // Updates that only matter when the tab is selected go here.
2228 // Updating the URL happens synchronously in ScheduleUIUpdate.
2229 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2230 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2231 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2234 if (flags & (content::INVALIDATE_TYPE_TAB |
2235 content::INVALIDATE_TYPE_TITLE)) {
2236 window_->UpdateTitleBar();
2240 // Updates that don't depend upon the selected state go here.
2241 if (flags &
2242 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2243 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2244 // is fixed.
2245 tracked_objects::ScopedTracker tracking_profile3(
2246 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2247 "467185 Browser::ProcessPendingUIUpdates3"));
2248 tab_strip_model_->UpdateWebContentsStateAt(
2249 tab_strip_model_->GetIndexOfWebContents(contents),
2250 TabStripModelObserver::ALL);
2253 // Update the bookmark bar. It may happen that the tab is crashed, and if
2254 // so, the bookmark bar should be hidden.
2255 if (flags & content::INVALIDATE_TYPE_TAB) {
2256 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2257 // is fixed.
2258 tracked_objects::ScopedTracker tracking_profile4(
2259 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2260 "467185 Browser::ProcessPendingUIUpdates4"));
2261 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2264 // We don't need to process INVALIDATE_STATE, since that's not visible.
2267 scheduled_updates_.clear();
2270 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2271 if (!contents)
2272 return;
2274 UpdateMap::iterator i = scheduled_updates_.find(contents);
2275 if (i != scheduled_updates_.end())
2276 scheduled_updates_.erase(i);
2279 ///////////////////////////////////////////////////////////////////////////////
2280 // Browser, Getters for UI (private):
2282 StatusBubble* Browser::GetStatusBubble() {
2283 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2284 if (chrome::IsRunningInAppMode())
2285 return NULL;
2287 return window_ ? window_->GetStatusBubble() : NULL;
2290 ///////////////////////////////////////////////////////////////////////////////
2291 // Browser, Session restore functions (private):
2293 void Browser::SyncHistoryWithTabs(int index) {
2294 SessionService* session_service =
2295 SessionServiceFactory::GetForProfileIfExisting(profile());
2296 if (session_service) {
2297 for (int i = index; i < tab_strip_model_->count(); ++i) {
2298 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2299 if (web_contents) {
2300 SessionTabHelper* session_tab_helper =
2301 SessionTabHelper::FromWebContents(web_contents);
2302 session_service->SetTabIndexInWindow(
2303 session_id(), session_tab_helper->session_id(), i);
2304 session_service->SetPinnedState(
2305 session_id(),
2306 session_tab_helper->session_id(),
2307 tab_strip_model_->IsTabPinned(i));
2313 ///////////////////////////////////////////////////////////////////////////////
2314 // Browser, In-progress download termination handling (private):
2316 bool Browser::CanCloseWithInProgressDownloads() {
2317 // If we've prompted, we need to hear from the user before we
2318 // can close.
2319 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2320 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2322 int num_downloads_blocking;
2323 Browser::DownloadClosePreventionType dialog_type =
2324 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2325 if (dialog_type == DOWNLOAD_CLOSE_OK)
2326 return true;
2328 // Closing this window will kill some downloads; prompt to make sure
2329 // that's ok.
2330 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2331 window_->ConfirmBrowserCloseWithPendingDownloads(
2332 num_downloads_blocking,
2333 dialog_type,
2334 false,
2335 base::Bind(&Browser::InProgressDownloadResponse,
2336 weak_factory_.GetWeakPtr()));
2338 // Return false so the browser does not close. We'll close if the user
2339 // confirms in the dialog.
2340 return false;
2343 ///////////////////////////////////////////////////////////////////////////////
2344 // Browser, Assorted utility functions (private):
2346 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2347 Browser* delegate = set_delegate ? this : NULL;
2348 // WebContents...
2349 web_contents->SetDelegate(delegate);
2351 // ...and all the helpers.
2352 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2353 WebContentsModalDialogManager::FromWebContents(web_contents)->
2354 SetDelegate(delegate);
2355 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2356 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2357 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2358 translate::ContentTranslateDriver& content_translate_driver =
2359 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2360 if (delegate) {
2361 ui_zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2362 content_translate_driver.AddObserver(this);
2363 } else {
2364 ui_zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(
2365 this);
2366 content_translate_driver.RemoveObserver(this);
2370 void Browser::CloseFrame() {
2371 window_->Close();
2374 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2375 int index,
2376 DetachType type) {
2377 if (type == DETACH_TYPE_DETACH) {
2378 // Save the current location bar state, but only if the tab being detached
2379 // is the selected tab. Because saving state can conditionally revert the
2380 // location bar, saving the current tab's location bar state to a
2381 // non-selected tab can corrupt both tabs.
2382 if (contents == tab_strip_model_->GetActiveWebContents()) {
2383 LocationBar* location_bar = window()->GetLocationBar();
2384 if (location_bar)
2385 location_bar->SaveStateToContents(contents);
2388 if (!tab_strip_model_->closing_all())
2389 SyncHistoryWithTabs(0);
2392 SetAsDelegate(contents, false);
2393 RemoveScheduledUpdatesFor(contents);
2395 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2396 find_bar_controller_->ChangeWebContents(NULL);
2399 // Stop observing search model changes for this tab.
2400 search_delegate_->OnTabDetached(contents);
2402 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2403 if (interstitial_observers_[i]->web_contents() != contents)
2404 continue;
2406 delete interstitial_observers_[i];
2407 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2408 return;
2412 bool Browser::ShouldShowLocationBar() const {
2413 // Tabbed browser always show a location bar.
2414 if (is_type_tabbed())
2415 return true;
2417 // Non-app windows that aren't tabbed or system windows should always show a
2418 // location bar, unless they are from a trusted source.
2419 if (!is_app())
2420 return !is_trusted_source();
2422 if (ShouldUseWebAppFrame())
2423 return false;
2425 // Bookmark apps should show the location bar.
2426 const std::string extension_id =
2427 web_app::GetExtensionIdFromApplicationName(app_name());
2428 const extensions::Extension* extension =
2429 extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
2430 extension_id, extensions::ExtensionRegistry::EVERYTHING);
2431 return extensions::ui_util::ShouldShowLocationBar(
2432 extension, tab_strip_model_->GetActiveWebContents());
2435 bool Browser::ShouldUseWebAppFrame() const {
2436 // Only use the web app frame for apps in ash, and only if the web app frame
2437 // is enabled.
2438 if (!is_app() || host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH ||
2439 !IsWebAppFrameEnabled()) {
2440 return false;
2443 // Use the web app frame for hosted apps.
2444 const std::string extension_id =
2445 web_app::GetExtensionIdFromApplicationName(app_name());
2446 const extensions::Extension* extension =
2447 extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
2448 extension_id, extensions::ExtensionRegistry::EVERYTHING);
2449 return extension && extension->from_bookmark();
2452 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2453 bool check_fullscreen) const {
2454 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2456 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2458 if (is_type_tabbed())
2459 features |= FEATURE_BOOKMARKBAR;
2461 if (!hide_ui_for_fullscreen) {
2462 if (!is_type_tabbed())
2463 features |= FEATURE_TITLEBAR;
2465 if (is_type_tabbed())
2466 features |= FEATURE_TABSTRIP;
2468 if (is_type_tabbed())
2469 features |= FEATURE_TOOLBAR;
2471 if (ShouldShowLocationBar())
2472 features |= FEATURE_LOCATIONBAR;
2474 if (ShouldUseWebAppFrame())
2475 features |= FEATURE_WEBAPPFRAME;
2477 return !!(features & feature);
2480 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2481 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2482 // fixed.
2483 tracked_objects::ScopedTracker tracking_profile1(
2484 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2485 "467185 Browser::UpdateBookmarkBarState1"));
2486 BookmarkBar::State state;
2487 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2488 // mode, unless on the new tab page.
2489 if (profile_->IsGuestSession()) {
2490 state = BookmarkBar::HIDDEN;
2491 } else if (browser_defaults::bookmarks_enabled &&
2492 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2493 !ShouldHideUIForFullscreen()) {
2494 state = BookmarkBar::SHOW;
2495 } else {
2496 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2497 // is fixed.
2498 tracked_objects::ScopedTracker tracking_profile2(
2499 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2500 "467185 Browser::UpdateBookmarkBarState2"));
2501 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2502 BookmarkTabHelper* bookmark_tab_helper =
2503 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2504 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2505 state = BookmarkBar::DETACHED;
2506 else
2507 state = BookmarkBar::HIDDEN;
2510 if (state == bookmark_bar_state_)
2511 return;
2513 bookmark_bar_state_ = state;
2515 if (!window_)
2516 return; // This is called from the constructor when window_ is NULL.
2518 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2519 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2520 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2521 // end up querying state once they process the tab switch.
2522 return;
2525 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2526 // fixed.
2527 tracked_objects::ScopedTracker tracking_profile3(
2528 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2529 "467185 Browser::UpdateBookmarkBarState3"));
2531 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2532 window_->BookmarkBarStateChanged(should_animate ?
2533 BookmarkBar::ANIMATE_STATE_CHANGE :
2534 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2537 bool Browser::ShouldHideUIForFullscreen() const {
2538 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2539 // keep the controls in a slide-down panel.
2540 return window_ && window_->ShouldHideUIForFullscreen();
2543 bool Browser::MaybeCreateBackgroundContents(
2544 int route_id,
2545 int main_frame_route_id,
2546 WebContents* opener_web_contents,
2547 const base::string16& frame_name,
2548 const GURL& target_url,
2549 const std::string& partition_id,
2550 content::SessionStorageNamespace* session_storage_namespace) {
2551 GURL opener_url = opener_web_contents->GetURL();
2552 ExtensionService* extensions_service =
2553 extensions::ExtensionSystem::Get(profile_)->extension_service();
2555 if (!opener_url.is_valid() ||
2556 frame_name.empty() ||
2557 !extensions_service ||
2558 !extensions_service->is_ready())
2559 return false;
2561 // Only hosted apps have web extents, so this ensures that only hosted apps
2562 // can create BackgroundContents. We don't have to check for background
2563 // permission as that is checked in RenderMessageFilter when the CreateWindow
2564 // message is processed.
2565 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
2566 ->enabled_extensions()
2567 .GetHostedAppByURL(opener_url);
2568 if (!extension)
2569 return false;
2571 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2572 BackgroundContentsService* service =
2573 BackgroundContentsServiceFactory::GetForProfile(profile_);
2574 if (!service)
2575 return false;
2577 // Ensure that we're trying to open this from the extension's process.
2578 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2579 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2580 if (!opener_site_instance->GetProcess() ||
2581 !process_map->Contains(
2582 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2583 return false;
2586 // Only allow a single background contents per app.
2587 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2588 BackgroundContents* existing =
2589 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2590 if (existing) {
2591 // For non-scriptable background contents, ignore the request altogether,
2592 // (returning true, so that a regular WebContents isn't created either).
2593 if (!allow_js_access)
2594 return true;
2595 // For scriptable background pages, if one already exists, close it (even
2596 // if it was specified in the manifest).
2597 delete existing;
2600 // If script access is not allowed, create the the background contents in a
2601 // new SiteInstance, so that a separate process is used.
2602 scoped_refptr<content::SiteInstance> site_instance =
2603 allow_js_access ?
2604 opener_site_instance :
2605 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2607 // Passed all the checks, so this should be created as a BackgroundContents.
2608 BackgroundContents* contents =
2609 service->CreateBackgroundContents(site_instance.get(),
2610 route_id,
2611 main_frame_route_id,
2612 profile_,
2613 frame_name,
2614 base::ASCIIToUTF16(extension->id()),
2615 partition_id,
2616 session_storage_namespace);
2618 // When a separate process is used, the original renderer cannot access the
2619 // new window later, thus we need to navigate the window now.
2620 if (contents && !allow_js_access) {
2621 contents->web_contents()->GetController().LoadURL(
2622 target_url,
2623 content::Referrer(),
2624 ui::PAGE_TRANSITION_LINK,
2625 std::string()); // No extra headers.
2628 return contents != NULL;