Componentize AccountReconcilor.
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob12dde57accf9cf12ebabe8852aca63b9be60c3de
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/path_service.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/process_info.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/time/time.h"
30 #include "chrome/app/chrome_command_ids.h"
31 #include "chrome/browser/app_mode/app_mode_utils.h"
32 #include "chrome/browser/autofill/personal_data_manager_factory.h"
33 #include "chrome/browser/background/background_contents_service.h"
34 #include "chrome/browser/background/background_contents_service_factory.h"
35 #include "chrome/browser/bookmarks/bookmark_model.h"
36 #include "chrome/browser/bookmarks/bookmark_utils.h"
37 #include "chrome/browser/browser_process.h"
38 #include "chrome/browser/browser_shutdown.h"
39 #include "chrome/browser/character_encoding.h"
40 #include "chrome/browser/chrome_notification_types.h"
41 #include "chrome/browser/chrome_page_zoom.h"
42 #include "chrome/browser/content_settings/host_content_settings_map.h"
43 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
44 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
45 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
46 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
47 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
48 #include "chrome/browser/defaults.h"
49 #include "chrome/browser/devtools/devtools_toggle_action.h"
50 #include "chrome/browser/devtools/devtools_window.h"
51 #include "chrome/browser/download/download_item_model.h"
52 #include "chrome/browser/download/download_service.h"
53 #include "chrome/browser/download/download_service_factory.h"
54 #include "chrome/browser/download/download_shelf.h"
55 #include "chrome/browser/extensions/browser_extension_window_controller.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/tab_helper.h"
58 #include "chrome/browser/favicon/favicon_tab_helper.h"
59 #include "chrome/browser/file_select_helper.h"
60 #include "chrome/browser/first_run/first_run.h"
61 #include "chrome/browser/google/google_url_tracker.h"
62 #include "chrome/browser/infobars/infobar_service.h"
63 #include "chrome/browser/infobars/simple_alert_infobar_delegate.h"
64 #include "chrome/browser/lifetime/application_lifetime.h"
65 #include "chrome/browser/notifications/notification_ui_manager.h"
66 #include "chrome/browser/pepper_broker_infobar_delegate.h"
67 #include "chrome/browser/prefs/incognito_mode_prefs.h"
68 #include "chrome/browser/profiles/profile.h"
69 #include "chrome/browser/profiles/profile_destroyer.h"
70 #include "chrome/browser/profiles/profile_manager.h"
71 #include "chrome/browser/profiles/profile_metrics.h"
72 #include "chrome/browser/repost_form_warning_controller.h"
73 #include "chrome/browser/search/search.h"
74 #include "chrome/browser/sessions/session_service.h"
75 #include "chrome/browser/sessions/session_service_factory.h"
76 #include "chrome/browser/sessions/session_tab_helper.h"
77 #include "chrome/browser/sessions/session_types.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/background_contents.h"
84 #include "chrome/browser/tab_contents/retargeting_details.h"
85 #include "chrome/browser/tab_contents/tab_util.h"
86 #include "chrome/browser/themes/theme_service.h"
87 #include "chrome/browser/themes/theme_service_factory.h"
88 #include "chrome/browser/translate/translate_tab_helper.h"
89 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
90 #include "chrome/browser/ui/autofill/tab_autofill_manager_delegate.h"
91 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
92 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
93 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
94 #include "chrome/browser/ui/browser_command_controller.h"
95 #include "chrome/browser/ui/browser_commands.h"
96 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
97 #include "chrome/browser/ui/browser_content_translate_driver_observer.h"
98 #include "chrome/browser/ui/browser_dialogs.h"
99 #include "chrome/browser/ui/browser_finder.h"
100 #include "chrome/browser/ui/browser_instant_controller.h"
101 #include "chrome/browser/ui/browser_iterator.h"
102 #include "chrome/browser/ui/browser_list.h"
103 #include "chrome/browser/ui/browser_navigator.h"
104 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
105 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
106 #include "chrome/browser/ui/browser_tabstrip.h"
107 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
108 #include "chrome/browser/ui/browser_ui_prefs.h"
109 #include "chrome/browser/ui/browser_window.h"
110 #include "chrome/browser/ui/chrome_pages.h"
111 #include "chrome/browser/ui/chrome_select_file_policy.h"
112 #include "chrome/browser/ui/fast_unload_controller.h"
113 #include "chrome/browser/ui/find_bar/find_bar.h"
114 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
115 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
116 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
117 #include "chrome/browser/ui/global_error/global_error.h"
118 #include "chrome/browser/ui/global_error/global_error_service.h"
119 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
120 #include "chrome/browser/ui/media_utils.h"
121 #include "chrome/browser/ui/omnibox/location_bar.h"
122 #include "chrome/browser/ui/search/search_delegate.h"
123 #include "chrome/browser/ui/search/search_model.h"
124 #include "chrome/browser/ui/search/search_tab_helper.h"
125 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
126 #include "chrome/browser/ui/singleton_tabs.h"
127 #include "chrome/browser/ui/status_bubble.h"
128 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
129 #include "chrome/browser/ui/tab_contents/core_tab_helper.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/toolbar/toolbar_model_impl.h"
135 #include "chrome/browser/ui/unload_controller.h"
136 #include "chrome/browser/ui/validation_message_bubble.h"
137 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
138 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
139 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
140 #include "chrome/browser/ui/window_sizer/window_sizer.h"
141 #include "chrome/browser/ui/zoom/zoom_controller.h"
142 #include "chrome/browser/upgrade_detector.h"
143 #include "chrome/browser/web_applications/web_app.h"
144 #include "chrome/common/chrome_constants.h"
145 #include "chrome/common/chrome_switches.h"
146 #include "chrome/common/custom_handlers/protocol_handler.h"
147 #include "chrome/common/net/url_fixer_upper.h"
148 #include "chrome/common/pref_names.h"
149 #include "chrome/common/profiling.h"
150 #include "chrome/common/search_types.h"
151 #include "chrome/common/url_constants.h"
152 #include "components/startup_metric_utils/startup_metric_utils.h"
153 #include "components/web_modal/web_contents_modal_dialog_manager.h"
154 #include "content/public/browser/devtools_manager.h"
155 #include "content/public/browser/download_item.h"
156 #include "content/public/browser/download_manager.h"
157 #include "content/public/browser/interstitial_page.h"
158 #include "content/public/browser/invalidate_type.h"
159 #include "content/public/browser/navigation_controller.h"
160 #include "content/public/browser/navigation_entry.h"
161 #include "content/public/browser/notification_details.h"
162 #include "content/public/browser/notification_service.h"
163 #include "content/public/browser/plugin_service.h"
164 #include "content/public/browser/render_process_host.h"
165 #include "content/public/browser/render_view_host.h"
166 #include "content/public/browser/render_widget_host_view.h"
167 #include "content/public/browser/site_instance.h"
168 #include "content/public/browser/user_metrics.h"
169 #include "content/public/browser/web_contents.h"
170 #include "content/public/browser/web_contents_view.h"
171 #include "content/public/common/content_switches.h"
172 #include "content/public/common/page_zoom.h"
173 #include "content/public/common/renderer_preferences.h"
174 #include "content/public/common/webplugininfo.h"
175 #include "extensions/browser/extension_prefs.h"
176 #include "extensions/browser/extension_system.h"
177 #include "extensions/common/constants.h"
178 #include "extensions/common/extension.h"
179 #include "extensions/common/manifest_handlers/background_info.h"
180 #include "grit/chromium_strings.h"
181 #include "grit/generated_resources.h"
182 #include "grit/locale_settings.h"
183 #include "grit/theme_resources.h"
184 #include "net/base/net_util.h"
185 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
186 #include "net/cookies/cookie_monster.h"
187 #include "net/url_request/url_request_context.h"
188 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
189 #include "ui/base/l10n/l10n_util.h"
190 #include "ui/base/window_open_disposition.h"
191 #include "ui/gfx/point.h"
192 #include "ui/shell_dialogs/selected_file_info.h"
194 #if defined(OS_WIN)
195 #include "base/win/metro.h"
196 #include "chrome/browser/ssl/ssl_error_info.h"
197 #include "chrome/browser/task_manager/task_manager.h"
198 #include "chrome/browser/ui/view_ids.h"
199 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
200 #include "ui/base/win/shell.h"
201 #endif // OS_WIN
203 #if defined(OS_CHROMEOS)
204 #include "chrome/browser/chromeos/drive/file_system_util.h"
205 #endif
207 #if defined(USE_ASH)
208 #include "ash/ash_switches.h"
209 #endif
211 using base::TimeDelta;
212 using base::UserMetricsAction;
213 using content::NativeWebKeyboardEvent;
214 using content::NavigationController;
215 using content::NavigationEntry;
216 using content::OpenURLParams;
217 using content::PluginService;
218 using content::Referrer;
219 using content::RenderWidgetHostView;
220 using content::SiteInstance;
221 using content::WebContents;
222 using extensions::Extension;
223 using ui::WebDialogDelegate;
224 using web_modal::WebContentsModalDialogManager;
225 using blink::WebWindowFeatures;
227 ///////////////////////////////////////////////////////////////////////////////
229 namespace {
231 // How long we wait before updating the browser chrome while loading a page.
232 const int kUIUpdateCoalescingTimeMS = 200;
234 BrowserWindow* CreateBrowserWindow(Browser* browser) {
235 return BrowserWindow::CreateBrowserWindow(browser);
238 // Is the fast tab unload experiment enabled?
239 bool IsFastTabUnloadEnabled() {
240 return CommandLine::ForCurrentProcess()->HasSwitch(
241 switches::kEnableFastUnload);
244 } // namespace
246 ////////////////////////////////////////////////////////////////////////////////
247 // Browser, CreateParams:
249 Browser::CreateParams::CreateParams(Profile* profile,
250 chrome::HostDesktopType host_desktop_type)
251 : type(TYPE_TABBED),
252 profile(profile),
253 host_desktop_type(host_desktop_type),
254 app_type(APP_TYPE_HOST),
255 initial_show_state(ui::SHOW_STATE_DEFAULT),
256 is_session_restore(false),
257 window(NULL) {
260 Browser::CreateParams::CreateParams(Type type,
261 Profile* profile,
262 chrome::HostDesktopType host_desktop_type)
263 : type(type),
264 profile(profile),
265 host_desktop_type(host_desktop_type),
266 app_type(APP_TYPE_HOST),
267 initial_show_state(ui::SHOW_STATE_DEFAULT),
268 is_session_restore(false),
269 window(NULL) {
272 // static
273 Browser::CreateParams Browser::CreateParams::CreateForApp(
274 Type type,
275 const std::string& app_name,
276 const gfx::Rect& window_bounds,
277 Profile* profile,
278 chrome::HostDesktopType host_desktop_type) {
279 DCHECK(type != TYPE_TABBED);
280 DCHECK(!app_name.empty());
282 CreateParams params(type, profile, host_desktop_type);
283 params.app_name = app_name;
284 params.app_type = APP_TYPE_CHILD;
285 params.initial_bounds = window_bounds;
287 return params;
290 // static
291 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
292 Profile* profile,
293 chrome::HostDesktopType host_desktop_type) {
294 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
295 params.app_name = DevToolsWindow::kDevToolsApp;
296 return params;
299 ////////////////////////////////////////////////////////////////////////////////
300 // Browser, InterstitialObserver:
302 class Browser::InterstitialObserver : public content::WebContentsObserver {
303 public:
304 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
305 : WebContentsObserver(web_contents),
306 browser_(browser) {
309 using content::WebContentsObserver::web_contents;
311 virtual void DidAttachInterstitialPage() OVERRIDE {
312 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
315 virtual void DidDetachInterstitialPage() OVERRIDE {
316 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
319 private:
320 Browser* browser_;
322 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
325 ///////////////////////////////////////////////////////////////////////////////
326 // Browser, Constructors, Creation, Showing:
328 Browser::Browser(const CreateParams& params)
329 : type_(params.type),
330 profile_(params.profile),
331 window_(NULL),
332 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
333 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(),
334 params.profile)),
335 app_name_(params.app_name),
336 app_type_(params.app_type),
337 cancel_download_confirmation_state_(NOT_PROMPTED),
338 override_bounds_(params.initial_bounds),
339 initial_show_state_(params.initial_show_state),
340 is_session_restore_(params.is_session_restore),
341 host_desktop_type_(BrowserWindow::AdjustHostDesktopType(
342 params.host_desktop_type)),
343 content_setting_bubble_model_delegate_(
344 new BrowserContentSettingBubbleModelDelegate(this)),
345 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
346 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
347 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
348 bookmark_bar_state_(BookmarkBar::HIDDEN),
349 command_controller_(new chrome::BrowserCommandController(
350 this, g_browser_process->profile_manager())),
351 window_has_shown_(false),
352 chrome_updater_factory_(this),
353 weak_factory_(this),
354 translate_driver_observer_(
355 new BrowserContentTranslateDriverObserver(this)) {
356 // If this causes a crash then a window is being opened using a profile type
357 // that is disallowed by policy. The crash prevents the disabled window type
358 // from opening at all, but the path that triggered it should be fixed.
359 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
360 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
361 << "Only off the record browser may be opened in guest mode";
363 // TODO(jeremy): Move to initializer list once flag is removed.
364 if (IsFastTabUnloadEnabled())
365 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
366 else
367 unload_controller_.reset(new chrome::UnloadController(this));
369 if (!app_name_.empty())
370 chrome::RegisterAppPrefs(app_name_, profile_);
371 tab_strip_model_->AddObserver(this);
373 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
374 search_model_.reset(new SearchModel());
375 search_delegate_.reset(new SearchDelegate(search_model_.get()));
377 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
378 content::Source<Profile>(profile_->GetOriginalProfile()));
379 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
380 content::Source<Profile>(profile_->GetOriginalProfile()));
381 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
382 content::Source<Profile>(profile_->GetOriginalProfile()));
383 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
384 content::NotificationService::AllSources());
385 #if defined(ENABLE_THEMES)
386 registrar_.Add(
387 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
388 content::Source<ThemeService>(
389 ThemeServiceFactory::GetForProfile(profile_)));
390 #endif
391 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
392 content::NotificationService::AllSources());
394 profile_pref_registrar_.Init(profile_->GetPrefs());
395 profile_pref_registrar_.Add(
396 prefs::kDevToolsDisabled,
397 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
398 profile_pref_registrar_.Add(
399 prefs::kShowBookmarkBar,
400 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
401 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
403 BrowserList::AddBrowser(this);
405 // NOTE: These prefs all need to be explicitly destroyed in the destructor
406 // or you'll get a nasty surprise when you run the incognito tests.
407 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
408 profile_->GetPrefs());
410 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
411 instant_controller_.reset(new BrowserInstantController(this));
413 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
415 ProfileMetrics::LogProfileLaunch(profile_);
417 window_ = params.window ? params.window : CreateBrowserWindow(this);
419 // Create the extension window controller before sending notifications.
420 extension_window_controller_.reset(
421 new BrowserExtensionWindowController(this));
423 SessionService* session_service =
424 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
425 if (session_service)
426 session_service->WindowOpened(this);
428 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
429 // replace uses of this with BL's notifications.
430 content::NotificationService::current()->Notify(
431 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
432 content::Source<Browser>(this),
433 content::NotificationService::NoDetails());
435 // TODO(beng): move to ChromeBrowserMain:
436 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
437 #if defined(OS_WIN)
438 // Notify PDM that this is a first run.
439 ImportAutofillDataWin(
440 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
441 #endif // defined(OS_WIN)
444 fullscreen_controller_.reset(new FullscreenController(this));
447 Browser::~Browser() {
448 // The tab strip should not have any tabs at this point.
449 DCHECK(tab_strip_model_->empty());
450 tab_strip_model_->RemoveObserver(this);
452 // Destroy the BrowserCommandController before removing the browser, so that
453 // it doesn't act on any notifications that are sent as a result of removing
454 // the browser.
455 command_controller_.reset();
456 BrowserList::RemoveBrowser(this);
458 SessionService* session_service =
459 SessionServiceFactory::GetForProfile(profile_);
460 if (session_service)
461 session_service->WindowClosed(session_id_);
463 TabRestoreService* tab_restore_service =
464 TabRestoreServiceFactory::GetForProfile(profile());
465 if (tab_restore_service)
466 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
468 #if !defined(OS_MACOSX)
469 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
470 // We're the last browser window with this profile. We need to nuke the
471 // TabRestoreService, which will start the shutdown of the
472 // NavigationControllers and allow for proper shutdown. If we don't do this
473 // chrome won't shutdown cleanly, and may end up crashing when some
474 // thread tries to use the IO thread (or another thread) that is no longer
475 // valid.
476 // This isn't a valid assumption for Mac OS, as it stays running after
477 // the last browser has closed. The Mac equivalent is in its app
478 // controller.
479 TabRestoreServiceFactory::ResetForProfile(profile_);
481 #endif
483 profile_pref_registrar_.RemoveAll();
485 encoding_auto_detect_.Destroy();
487 // Destroy BrowserExtensionWindowController before the incognito profile
488 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
489 extension_window_controller_.reset();
491 // Destroy BrowserInstantController before the incongnito profile is destroyed
492 // because the InstantController destructor depends on this profile.
493 instant_controller_.reset();
495 if (profile_->IsOffTheRecord() &&
496 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
497 // An incognito profile is no longer needed, this indirectly frees
498 // its cache and cookies once it gets destroyed at the appropriate time.
499 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
502 // There may be pending file dialogs, we need to tell them that we've gone
503 // away so they don't try and call back to us.
504 if (select_file_dialog_.get())
505 select_file_dialog_->ListenerDestroyed();
507 int num_downloads;
508 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
509 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
510 !browser_defaults::kBrowserAliveWithNoWindows) {
511 DownloadService::CancelAllDownloads();
515 ///////////////////////////////////////////////////////////////////////////////
516 // Getters & Setters
518 FindBarController* Browser::GetFindBarController() {
519 if (!find_bar_controller_.get()) {
520 FindBar* find_bar = window_->CreateFindBar();
521 find_bar_controller_.reset(new FindBarController(find_bar));
522 find_bar->SetFindBarController(find_bar_controller_.get());
523 find_bar_controller_->ChangeWebContents(
524 tab_strip_model_->GetActiveWebContents());
525 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
527 return find_bar_controller_.get();
530 bool Browser::HasFindBarController() const {
531 return find_bar_controller_.get() != NULL;
534 bool Browser::is_app() const {
535 return !app_name_.empty();
538 bool Browser::is_devtools() const {
539 return app_name_ == DevToolsWindow::kDevToolsApp;
542 ///////////////////////////////////////////////////////////////////////////////
543 // Browser, State Storage and Retrieval for UI:
545 gfx::Image Browser::GetCurrentPageIcon() const {
546 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
547 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
548 // window during the window's creation (before tabs have been added).
549 FaviconTabHelper* favicon_tab_helper =
550 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
551 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
554 base::string16 Browser::GetWindowTitleForCurrentTab() const {
555 WebContents* contents = tab_strip_model_->GetActiveWebContents();
556 base::string16 title;
558 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
559 // window during the window's creation (before tabs have been added).
560 if (contents) {
561 title = contents->GetTitle();
562 FormatTitleForDisplay(&title);
564 if (title.empty())
565 title = CoreTabHelper::GetDefaultTitle();
567 #if defined(OS_MACOSX)
568 // On Mac, we don't want to suffix the page title with
569 // the application name.
570 return title;
571 #elif defined(USE_ASH)
572 // On Ash, we don't want to suffix the page title with the application name,
573 // but on Windows, where USE_ASH can also be true, we still want the prefix
574 // on desktop.
575 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
576 return title;
577 #endif
578 // Don't append the app name to window titles on app frames and app popups
579 return is_app() ?
580 title :
581 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
584 // static
585 void Browser::FormatTitleForDisplay(base::string16* title) {
586 size_t current_index = 0;
587 size_t match_index;
588 while ((match_index = title->find(L'\n', current_index)) !=
589 base::string16::npos) {
590 title->replace(match_index, 1, base::string16());
591 current_index = match_index;
595 ///////////////////////////////////////////////////////////////////////////////
596 // Browser, OnBeforeUnload handling:
598 bool Browser::ShouldCloseWindow() {
599 if (!CanCloseWithInProgressDownloads())
600 return false;
602 if (IsFastTabUnloadEnabled())
603 return fast_unload_controller_->ShouldCloseWindow();
604 return unload_controller_->ShouldCloseWindow();
607 bool Browser::CallBeforeUnloadHandlers(
608 const base::Callback<void(bool)>& on_close_confirmed) {
609 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
610 if (IsFastTabUnloadEnabled()) {
611 return fast_unload_controller_->CallBeforeUnloadHandlers(
612 on_close_confirmed);
614 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
617 void Browser::ResetBeforeUnloadHandlers() {
618 cancel_download_confirmation_state_ = NOT_PROMPTED;
619 if (IsFastTabUnloadEnabled())
620 fast_unload_controller_->ResetBeforeUnloadHandlers();
621 else
622 unload_controller_->ResetBeforeUnloadHandlers();
625 bool Browser::HasCompletedUnloadProcessing() const {
626 DCHECK(IsFastTabUnloadEnabled());
627 return fast_unload_controller_->HasCompletedUnloadProcessing();
630 bool Browser::IsAttemptingToCloseBrowser() const {
631 if (IsFastTabUnloadEnabled())
632 return fast_unload_controller_->is_attempting_to_close_browser();
633 return unload_controller_->is_attempting_to_close_browser();
636 void Browser::OnWindowClosing() {
637 if (!ShouldCloseWindow())
638 return;
640 // Application should shutdown on last window close if the user is explicitly
641 // trying to quit, or if there is nothing keeping the browser alive (such as
642 // AppController on the Mac, or BackgroundContentsService for background
643 // pages).
644 bool should_quit_if_last_browser =
645 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
647 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this))
648 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
650 // Don't use GetForProfileIfExisting here, we want to force creation of the
651 // session service so that user can restore what was open.
652 SessionService* session_service =
653 SessionServiceFactory::GetForProfile(profile());
654 if (session_service)
655 session_service->WindowClosing(session_id());
657 TabRestoreService* tab_restore_service =
658 TabRestoreServiceFactory::GetForProfile(profile());
660 #if defined(USE_AURA)
661 if (tab_restore_service && is_app() && !is_devtools())
662 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
663 #endif
665 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
666 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
668 // TODO(sky): convert session/tab restore to use notification.
669 content::NotificationService::current()->Notify(
670 chrome::NOTIFICATION_BROWSER_CLOSING,
671 content::Source<Browser>(this),
672 content::NotificationService::NoDetails());
674 if (!IsFastTabUnloadEnabled())
675 tab_strip_model_->CloseAllTabs();
678 ////////////////////////////////////////////////////////////////////////////////
679 // In-progress download termination handling:
681 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
682 if (cancel_downloads) {
683 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
684 chrome::CloseWindow(this);
685 return;
688 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
689 // close again we'll show the warning again.
690 cancel_download_confirmation_state_ = NOT_PROMPTED;
692 // Show the download page so the user can figure-out what downloads are still
693 // in-progress.
694 chrome::ShowDownloads(this);
696 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
697 // prompt every time any tab is closed. http://crbug.com/305516
698 if (IsFastTabUnloadEnabled())
699 fast_unload_controller_->CancelWindowClose();
700 else
701 unload_controller_->CancelWindowClose();
704 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
705 int* num_downloads_blocking) const {
706 DCHECK(num_downloads_blocking);
707 *num_downloads_blocking = 0;
709 // If we're not running a full browser process with a profile manager
710 // (testing), it's ok to close the browser.
711 if (!g_browser_process->profile_manager())
712 return DOWNLOAD_CLOSE_OK;
714 int total_download_count =
715 DownloadService::NonMaliciousDownloadCountAllProfiles();
716 if (total_download_count == 0)
717 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
719 // Figure out how many windows are open total, and associated with this
720 // profile, that are relevant for the ok-to-close decision.
721 int profile_window_count = 0;
722 int total_window_count = 0;
723 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
724 // Don't count this browser window or any other in the process of closing.
725 Browser* const browser = *it;
726 // Window closing may be delayed, and windows that are in the process of
727 // closing don't count against our totals.
728 if (browser == this || browser->IsAttemptingToCloseBrowser())
729 continue;
731 if (it->profile() == profile())
732 profile_window_count++;
733 total_window_count++;
736 // If there aren't any other windows, we're at browser shutdown,
737 // which would cancel all current downloads.
738 if (total_window_count == 0) {
739 *num_downloads_blocking = total_download_count;
740 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
743 // If there aren't any other windows on our profile, and we're an incognito
744 // profile, and there are downloads associated with that profile,
745 // those downloads would be cancelled by our window (-> profile) close.
746 DownloadService* download_service =
747 DownloadServiceFactory::GetForBrowserContext(profile());
748 if ((profile_window_count == 0) &&
749 (download_service->NonMaliciousDownloadCount() > 0) &&
750 profile()->IsOffTheRecord()) {
751 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
752 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
755 // Those are the only conditions under which we will block shutdown.
756 return DOWNLOAD_CLOSE_OK;
759 ////////////////////////////////////////////////////////////////////////////////
760 // Browser, Tab adding/showing functions:
762 void Browser::WindowFullscreenStateChanged() {
763 fullscreen_controller_->WindowFullscreenStateChanged();
764 command_controller_->FullscreenStateChanged();
765 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
768 void Browser::VisibleSSLStateChanged(content::WebContents* web_contents) {
769 // When the current tab's SSL state changes, we need to update the URL
770 // bar to reflect the new state.
771 DCHECK(web_contents);
772 if (tab_strip_model_->GetActiveWebContents() == web_contents)
773 UpdateToolbar(false);
776 void Browser::OnWebContentsInstantSupportDisabled(
777 const content::WebContents* web_contents) {
778 DCHECK(web_contents);
779 if (tab_strip_model_->GetActiveWebContents() == web_contents)
780 UpdateToolbar(false);
783 ///////////////////////////////////////////////////////////////////////////////
784 // Browser, Assorted browser commands:
786 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
787 fullscreen_controller_->
788 ToggleBrowserFullscreenModeWithExtension(extension_url);
791 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
792 return SupportsWindowFeatureImpl(feature, true);
795 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
796 return SupportsWindowFeatureImpl(feature, false);
799 void Browser::ToggleEncodingAutoDetect() {
800 content::RecordAction(UserMetricsAction("AutoDetectChange"));
801 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
802 // If "auto detect" is turned on, then any current override encoding
803 // is cleared. This also implicitly performs a reload.
804 // OTOH, if "auto detect" is turned off, we don't change the currently
805 // active encoding.
806 if (encoding_auto_detect_.GetValue()) {
807 WebContents* contents = tab_strip_model_->GetActiveWebContents();
808 if (contents)
809 contents->ResetOverrideEncoding();
813 void Browser::OverrideEncoding(int encoding_id) {
814 content::RecordAction(UserMetricsAction("OverrideEncoding"));
815 const std::string selected_encoding =
816 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
817 WebContents* contents = tab_strip_model_->GetActiveWebContents();
818 if (!selected_encoding.empty() && contents)
819 contents->SetOverrideEncoding(selected_encoding);
820 // Update the list of recently selected encodings.
821 std::string new_selected_encoding_list;
822 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
823 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
824 encoding_id,
825 &new_selected_encoding_list)) {
826 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
827 new_selected_encoding_list);
831 void Browser::OpenFile() {
832 content::RecordAction(UserMetricsAction("OpenFile"));
833 select_file_dialog_ = ui::SelectFileDialog::Create(
834 this, new ChromeSelectFilePolicy(
835 tab_strip_model_->GetActiveWebContents()));
837 const base::FilePath directory = profile_->last_selected_directory();
839 // TODO(beng): figure out how to juggle this.
840 gfx::NativeWindow parent_window = window_->GetNativeWindow();
841 ui::SelectFileDialog::FileTypeInfo file_types;
842 file_types.support_drive = true;
843 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
844 base::string16(),
845 directory,
846 &file_types,
848 base::FilePath::StringType(),
849 parent_window,
850 NULL);
853 void Browser::UpdateDownloadShelfVisibility(bool visible) {
854 if (GetStatusBubble())
855 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
858 ///////////////////////////////////////////////////////////////////////////////
860 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
861 content::PageTransition transition,
862 bool user_initiated) {
863 tab_strip_model_->TabNavigating(contents, transition);
865 bool contents_is_selected =
866 contents == tab_strip_model_->GetActiveWebContents();
867 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
868 // Forcibly reset the location bar if the url is going to change in the
869 // current tab, since otherwise it won't discard any ongoing user edits,
870 // since it doesn't realize this is a user-initiated action.
871 window()->GetLocationBar()->Revert();
874 if (GetStatusBubble())
875 GetStatusBubble()->Hide();
877 // Update the location bar. This is synchronous. We specifically don't
878 // update the load state since the load hasn't started yet and updating it
879 // will put it out of sync with the actual state like whether we're
880 // displaying a favicon, which controls the throbber. If we updated it here,
881 // the throbber will show the default favicon for a split second when
882 // navigating away from the new tab page.
883 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
885 if (contents_is_selected)
886 contents->GetView()->SetInitialFocus();
889 ///////////////////////////////////////////////////////////////////////////////
890 // Browser, PageNavigator implementation:
892 WebContents* Browser::OpenURL(const OpenURLParams& params) {
893 return OpenURLFromTab(NULL, params);
896 ///////////////////////////////////////////////////////////////////////////////
897 // Browser, TabStripModelObserver implementation:
899 void Browser::TabInsertedAt(WebContents* contents,
900 int index,
901 bool foreground) {
902 SetAsDelegate(contents, this);
903 SessionTabHelper* session_tab_helper =
904 SessionTabHelper::FromWebContents(contents);
905 session_tab_helper->SetWindowID(session_id());
907 content::NotificationService::current()->Notify(
908 chrome::NOTIFICATION_TAB_PARENTED,
909 content::Source<content::WebContents>(contents),
910 content::NotificationService::NoDetails());
912 SyncHistoryWithTabs(index);
914 // Make sure the loading state is updated correctly, otherwise the throbber
915 // won't start if the page is loading.
916 LoadingStateChanged(contents, true);
918 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
920 SessionService* session_service =
921 SessionServiceFactory::GetForProfile(profile_);
922 if (session_service) {
923 session_service->TabInserted(contents);
924 int new_active_index = tab_strip_model_->active_index();
925 if (index < new_active_index)
926 session_service->SetSelectedTabInWindow(session_id(),
927 new_active_index);
931 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
932 WebContents* contents,
933 int index) {
934 fullscreen_controller_->OnTabClosing(contents);
935 SessionService* session_service =
936 SessionServiceFactory::GetForProfile(profile_);
937 if (session_service)
938 session_service->TabClosing(contents);
939 content::NotificationService::current()->Notify(
940 chrome::NOTIFICATION_TAB_CLOSING,
941 content::Source<NavigationController>(&contents->GetController()),
942 content::NotificationService::NoDetails());
944 // Sever the WebContents' connection back to us.
945 SetAsDelegate(contents, NULL);
948 void Browser::TabDetachedAt(WebContents* contents, int index) {
949 // TabDetachedAt is called before TabStripModel has updated the
950 // active index.
951 int old_active_index = tab_strip_model_->active_index();
952 if (index < old_active_index && !tab_strip_model_->closing_all()) {
953 SessionService* session_service =
954 SessionServiceFactory::GetForProfileIfExisting(profile_);
955 if (session_service)
956 session_service->SetSelectedTabInWindow(session_id(),
957 old_active_index - 1);
959 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
962 void Browser::TabDeactivated(WebContents* contents) {
963 fullscreen_controller_->OnTabDeactivated(contents);
964 search_delegate_->OnTabDeactivated(contents);
965 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
967 // Save what the user's currently typing, so it can be restored when we
968 // switch back to this tab.
969 window_->GetLocationBar()->SaveStateToContents(contents);
971 if (instant_controller_)
972 instant_controller_->TabDeactivated(contents);
975 void Browser::ActiveTabChanged(WebContents* old_contents,
976 WebContents* new_contents,
977 int index,
978 int reason) {
979 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
981 // Update the bookmark state, since the BrowserWindow may query it during
982 // OnActiveTabChanged() below.
983 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
985 // Let the BrowserWindow do its handling. On e.g. views this changes the
986 // focused object, which should happen before we update the toolbar below,
987 // since the omnibox expects the correct element to already be focused when it
988 // is updated.
989 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
991 fullscreen_controller_->OnTabDetachedFromView(old_contents);
993 // Discarded tabs always get reloaded.
994 if (tab_strip_model_->IsTabDiscarded(index)) {
995 LOG(WARNING) << "Reloading discarded tab at " << index;
996 static int reload_count = 0;
997 UMA_HISTOGRAM_CUSTOM_COUNTS(
998 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
999 chrome::Reload(this, CURRENT_TAB);
1002 // If we have any update pending, do it now.
1003 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1004 ProcessPendingUIUpdates();
1006 // Propagate the profile to the location bar.
1007 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1009 if (chrome::IsInstantExtendedAPIEnabled())
1010 search_delegate_->OnTabActivated(new_contents);
1012 // Update reload/stop state.
1013 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1015 // Update commands to reflect current state.
1016 command_controller_->TabStateChanged();
1018 // Reset the status bubble.
1019 StatusBubble* status_bubble = GetStatusBubble();
1020 if (status_bubble) {
1021 status_bubble->Hide();
1023 // Show the loading state (if any).
1024 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1025 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1028 if (HasFindBarController()) {
1029 find_bar_controller_->ChangeWebContents(new_contents);
1030 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1033 // Update sessions. Don't force creation of sessions. If sessions doesn't
1034 // exist, the change will be picked up by sessions when created.
1035 SessionService* session_service =
1036 SessionServiceFactory::GetForProfileIfExisting(profile_);
1037 if (session_service && !tab_strip_model_->closing_all()) {
1038 session_service->SetSelectedTabInWindow(session_id(),
1039 tab_strip_model_->active_index());
1042 // This needs to be called after notifying SearchDelegate.
1043 if (instant_controller_)
1044 instant_controller_->ActiveTabChanged();
1046 autofill::TabAutofillManagerDelegate::FromWebContents(new_contents)->
1047 TabActivated();
1048 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1051 void Browser::TabMoved(WebContents* contents,
1052 int from_index,
1053 int to_index) {
1054 DCHECK(from_index >= 0 && to_index >= 0);
1055 // Notify the history service.
1056 SyncHistoryWithTabs(std::min(from_index, to_index));
1059 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1060 WebContents* old_contents,
1061 WebContents* new_contents,
1062 int index) {
1063 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1064 fullscreen_controller_->OnTabClosing(old_contents);
1065 SessionService* session_service =
1066 SessionServiceFactory::GetForProfile(profile_);
1067 if (session_service)
1068 session_service->TabClosing(old_contents);
1069 TabInsertedAt(new_contents,
1070 index,
1071 (index == tab_strip_model_->active_index()));
1073 int entry_count = new_contents->GetController().GetEntryCount();
1074 if (entry_count > 0) {
1075 // Send out notification so that observers are updated appropriately.
1076 new_contents->GetController().NotifyEntryChanged(
1077 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1078 entry_count - 1);
1081 if (session_service) {
1082 // The new_contents may end up with a different navigation stack. Force
1083 // the session service to update itself.
1084 session_service->TabRestored(new_contents,
1085 tab_strip_model_->IsTabPinned(index));
1089 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1090 SessionService* session_service =
1091 SessionServiceFactory::GetForProfileIfExisting(profile());
1092 if (session_service) {
1093 SessionTabHelper* session_tab_helper =
1094 SessionTabHelper::FromWebContents(contents);
1095 session_service->SetPinnedState(session_id(),
1096 session_tab_helper->session_id(),
1097 tab_strip_model_->IsTabPinned(index));
1101 void Browser::TabStripEmpty() {
1102 // Close the frame after we return to the message loop (not immediately,
1103 // otherwise it will destroy this object before the stack has a chance to
1104 // cleanly unwind.)
1105 // Note: This will be called several times if TabStripEmpty is called several
1106 // times. This is because it does not close the window if tabs are
1107 // still present.
1108 base::MessageLoop::current()->PostTask(
1109 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1111 // Instant may have visible WebContents that need to be detached before the
1112 // window system closes.
1113 instant_controller_.reset();
1116 bool Browser::CanOverscrollContent() const {
1117 #if defined(USE_AURA)
1118 const std::string value = CommandLine::ForCurrentProcess()->
1119 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation);
1120 bool overscroll_enabled = value != "0";
1121 if (!overscroll_enabled)
1122 return false;
1123 if (is_app() || is_devtools() || !is_type_tabbed())
1124 return false;
1126 // The detached bookmark bar has appearance of floating above the
1127 // web-contents. This does not play nicely with overscroll navigation
1128 // gestures. So disable overscroll navigation when the bookmark bar is in the
1129 // detached state and the overscroll effect moves the layers.
1130 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1131 return false;
1132 return true;
1133 #else
1134 return false;
1135 #endif
1138 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1139 const NativeWebKeyboardEvent& event,
1140 bool* is_keyboard_shortcut) {
1141 // Escape exits tabbed fullscreen mode.
1142 // TODO(koz): Write a test for this http://crbug.com/100441.
1143 if (event.windowsKeyCode == 27 &&
1144 fullscreen_controller_->HandleUserPressedEscape()) {
1145 return true;
1147 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1150 void Browser::HandleKeyboardEvent(content::WebContents* source,
1151 const NativeWebKeyboardEvent& event) {
1152 window()->HandleKeyboardEvent(event);
1155 bool Browser::TabsNeedBeforeUnloadFired() {
1156 if (IsFastTabUnloadEnabled())
1157 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1158 return unload_controller_->TabsNeedBeforeUnloadFired();
1161 void Browser::OverscrollUpdate(int delta_y) {
1162 window_->OverscrollUpdate(delta_y);
1165 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1166 const gfx::Rect& anchor_in_root_view,
1167 const base::string16& main_text,
1168 const base::string16& sub_text) {
1169 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1170 if (rwhv) {
1171 validation_message_bubble_ =
1172 chrome::ValidationMessageBubble::CreateAndShow(
1173 rwhv->GetRenderWidgetHost(),
1174 anchor_in_root_view,
1175 main_text,
1176 sub_text);
1180 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1181 validation_message_bubble_.reset();
1184 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1185 const gfx::Rect& anchor_in_root_view) {
1186 if (!validation_message_bubble_)
1187 return;
1188 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1189 if (rwhv) {
1190 validation_message_bubble_->SetPositionRelativeToAnchor(
1191 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1195 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1196 const blink::WebGestureEvent& event) {
1197 // Disable pinch zooming in undocked dev tools window due to poor UX.
1198 if (app_name() == DevToolsWindow::kDevToolsApp)
1199 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1200 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1201 event.type == blink::WebGestureEvent::GesturePinchEnd;
1203 return false;
1206 bool Browser::IsMouseLocked() const {
1207 return fullscreen_controller_->IsMouseLocked();
1210 void Browser::OnWindowDidShow() {
1211 if (window_has_shown_)
1212 return;
1213 window_has_shown_ = true;
1215 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1216 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1217 // Measure the latency from startup till the first browser window becomes
1218 // visible.
1219 static bool is_first_browser_window = true;
1220 if (is_first_browser_window &&
1221 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1222 is_first_browser_window = false;
1223 const base::Time process_creation_time =
1224 base::CurrentProcessInfo::CreationTime();
1226 if (!process_creation_time.is_null()) {
1227 UMA_HISTOGRAM_LONG_TIMES(
1228 "Startup.BrowserWindowDisplay",
1229 base::Time::Now() - process_creation_time);
1232 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1234 // Nothing to do for non-tabbed windows.
1235 if (!is_type_tabbed())
1236 return;
1238 // Show any pending global error bubble.
1239 GlobalErrorService* service =
1240 GlobalErrorServiceFactory::GetForProfile(profile());
1241 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1242 if (error)
1243 error->ShowBubbleView(this);
1246 void Browser::ShowFirstRunBubble() {
1247 window()->GetLocationBar()->ShowFirstRunBubble();
1250 void Browser::ShowDownload(content::DownloadItem* download) {
1251 if (!window())
1252 return;
1254 // If the download occurs in a new tab, and it's not a save page
1255 // download (started before initial navigation completed) close it.
1256 WebContents* source = download->GetWebContents();
1257 if (source && source->GetController().IsInitialNavigation() &&
1258 tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1259 CloseContents(source);
1262 // Some (app downloads) are not supposed to appear on the shelf.
1263 if (!DownloadItemModel(download).ShouldShowInShelf())
1264 return;
1266 // GetDownloadShelf creates the download shelf if it was not yet created.
1267 DownloadShelf* shelf = window()->GetDownloadShelf();
1268 shelf->AddDownload(download);
1271 ///////////////////////////////////////////////////////////////////////////////
1272 // Browser, content::WebContentsDelegate implementation:
1274 WebContents* Browser::OpenURLFromTab(WebContents* source,
1275 const OpenURLParams& params) {
1276 chrome::NavigateParams nav_params(this, params.url, params.transition);
1277 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1278 nav_params.source_contents = source;
1279 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1280 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1281 nav_params.user_gesture = params.user_gesture;
1283 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1284 if (source)
1285 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1287 if (popup_blocker_helper) {
1288 if ((params.disposition == NEW_POPUP ||
1289 params.disposition == NEW_FOREGROUND_TAB ||
1290 params.disposition == NEW_BACKGROUND_TAB ||
1291 params.disposition == NEW_WINDOW) &&
1292 !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1293 switches::kDisablePopupBlocking)) {
1294 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1295 WebWindowFeatures())) {
1296 return NULL;
1301 chrome::Navigate(&nav_params);
1303 return nav_params.target_contents;
1306 void Browser::NavigationStateChanged(const WebContents* source,
1307 unsigned changed_flags) {
1308 // Only update the UI when something visible has changed.
1309 if (changed_flags)
1310 ScheduleUIUpdate(source, changed_flags);
1312 // We can synchronously update commands since they will only change once per
1313 // navigation, so we don't have to worry about flickering. We do, however,
1314 // need to update the command state early on load to always present usable
1315 // actions in the face of slow-to-commit pages.
1316 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1317 content::INVALIDATE_TYPE_LOAD))
1318 command_controller_->TabStateChanged();
1321 void Browser::AddNewContents(WebContents* source,
1322 WebContents* new_contents,
1323 WindowOpenDisposition disposition,
1324 const gfx::Rect& initial_pos,
1325 bool user_gesture,
1326 bool* was_blocked) {
1327 chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1328 user_gesture, was_blocked);
1331 void Browser::ActivateContents(WebContents* contents) {
1332 tab_strip_model_->ActivateTabAt(
1333 tab_strip_model_->GetIndexOfWebContents(contents), false);
1334 window_->Activate();
1337 void Browser::DeactivateContents(WebContents* contents) {
1338 window_->Deactivate();
1341 void Browser::LoadingStateChanged(WebContents* source,
1342 bool to_different_document) {
1343 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1344 window_->UpdateTitleBar();
1346 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1347 if (source == selected_contents) {
1348 bool is_loading = source->IsLoading() && to_different_document;
1349 command_controller_->LoadingStateChanged(is_loading, false);
1350 if (GetStatusBubble()) {
1351 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1352 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1357 void Browser::CloseContents(WebContents* source) {
1358 bool can_close_contents;
1359 if (IsFastTabUnloadEnabled())
1360 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1361 else
1362 can_close_contents = unload_controller_->CanCloseContents(source);
1364 if (can_close_contents)
1365 chrome::CloseWebContents(this, source, true);
1368 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1369 if (!IsPopupOrPanel(source)) {
1370 NOTREACHED() << "moving invalid browser type";
1371 return;
1373 window_->SetBounds(pos);
1376 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1377 return is_type_popup();
1380 void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1381 const GURL& url) {
1382 if (!GetStatusBubble())
1383 return;
1385 if (source == tab_strip_model_->GetActiveWebContents()) {
1386 PrefService* prefs = profile_->GetPrefs();
1387 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1391 void Browser::ContentsMouseEvent(
1392 WebContents* source, const gfx::Point& location, bool motion) {
1393 if (!GetStatusBubble())
1394 return;
1396 if (source == tab_strip_model_->GetActiveWebContents()) {
1397 GetStatusBubble()->MouseMoved(location, !motion);
1398 if (!motion)
1399 GetStatusBubble()->SetURL(GURL(), std::string());
1403 void Browser::ContentsZoomChange(bool zoom_in) {
1404 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1407 void Browser::WebContentsFocused(WebContents* contents) {
1408 window_->WebContentsFocused(contents);
1411 bool Browser::TakeFocus(content::WebContents* source,
1412 bool reverse) {
1413 content::NotificationService::current()->Notify(
1414 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1415 content::Source<Browser>(this),
1416 content::NotificationService::NoDetails());
1417 return false;
1420 gfx::Rect Browser::GetRootWindowResizerRect() const {
1421 return window_->GetRootWindowResizerRect();
1424 void Browser::BeforeUnloadFired(WebContents* web_contents,
1425 bool proceed,
1426 bool* proceed_to_fire_unload) {
1427 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1428 proceed, proceed_to_fire_unload))
1429 return;
1431 if (IsFastTabUnloadEnabled()) {
1432 *proceed_to_fire_unload =
1433 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1434 } else {
1435 *proceed_to_fire_unload =
1436 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1440 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1441 const content::NavigationEntry* entry =
1442 source->GetController().GetActiveEntry();
1443 if (entry) {
1444 GURL url = entry->GetURL();
1445 GURL virtual_url = entry->GetVirtualURL();
1446 if ((url.SchemeIs(content::kChromeUIScheme) &&
1447 url.host() == chrome::kChromeUINewTabHost) ||
1448 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1449 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1450 return true;
1454 return chrome::NavEntryIsInstantNTP(source, entry);
1457 void Browser::SetFocusToLocationBar(bool select_all) {
1458 // Two differences between this and FocusLocationBar():
1459 // (1) This doesn't get recorded in user metrics, since it's called
1460 // internally.
1461 // (2) This checks whether the location bar can be focused, and if not, clears
1462 // the focus. FocusLocationBar() is only reached when the location bar is
1463 // focusable, but this may be reached at other times, e.g. while in
1464 // fullscreen mode, where we need to leave focus in a consistent state.
1465 window_->SetFocusToLocationBar(select_all);
1468 int Browser::GetExtraRenderViewHeight() const {
1469 return window_->GetExtraRenderViewHeight();
1472 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1473 DCHECK(source);
1474 chrome::ViewSource(this, source);
1477 void Browser::ViewSourceForFrame(WebContents* source,
1478 const GURL& frame_url,
1479 const content::PageState& frame_page_state) {
1480 DCHECK(source);
1481 chrome::ViewSource(this, source, frame_url, frame_page_state);
1484 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1485 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1486 source);
1489 bool Browser::ShouldCreateWebContents(
1490 WebContents* web_contents,
1491 int route_id,
1492 WindowContainerType window_container_type,
1493 const base::string16& frame_name,
1494 const GURL& target_url,
1495 const std::string& partition_id,
1496 content::SessionStorageNamespace* session_storage_namespace) {
1497 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1498 // If a BackgroundContents is created, suppress the normal WebContents.
1499 return !MaybeCreateBackgroundContents(route_id,
1500 web_contents,
1501 frame_name,
1502 target_url,
1503 partition_id,
1504 session_storage_namespace);
1507 return true;
1510 void Browser::WebContentsCreated(WebContents* source_contents,
1511 int opener_render_frame_id,
1512 const base::string16& frame_name,
1513 const GURL& target_url,
1514 WebContents* new_contents) {
1515 // Adopt the WebContents now, so all observers are in place, as the network
1516 // requests for its initial navigation will start immediately. The WebContents
1517 // will later be inserted into this browser using Browser::Navigate via
1518 // AddNewContents.
1519 TabHelpers::AttachTabHelpers(new_contents);
1521 // Notify.
1522 RetargetingDetails details;
1523 details.source_web_contents = source_contents;
1524 details.source_render_frame_id = opener_render_frame_id;
1525 details.target_url = target_url;
1526 details.target_web_contents = new_contents;
1527 details.not_yet_in_tabstrip = true;
1528 content::NotificationService::current()->Notify(
1529 chrome::NOTIFICATION_RETARGETING,
1530 content::Source<Profile>(profile_),
1531 content::Details<RetargetingDetails>(&details));
1534 void Browser::RendererUnresponsive(WebContents* source) {
1535 // Ignore hangs if a tab is blocked.
1536 int index = tab_strip_model_->GetIndexOfWebContents(source);
1537 DCHECK_NE(TabStripModel::kNoTab, index);
1538 if (tab_strip_model_->IsTabBlocked(index))
1539 return;
1541 chrome::ShowHungRendererDialog(source);
1544 void Browser::RendererResponsive(WebContents* source) {
1545 chrome::HideHungRendererDialog(source);
1548 void Browser::WorkerCrashed(WebContents* source) {
1549 SimpleAlertInfoBarDelegate::Create(
1550 InfoBarService::FromWebContents(source), InfoBarDelegate::kNoIconID,
1551 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1554 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1555 if (web_contents == tab_strip_model_->GetActiveWebContents())
1556 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1559 void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1560 if (web_contents == tab_strip_model_->GetActiveWebContents())
1561 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1564 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1565 return GetJavaScriptDialogManagerInstance();
1568 content::ColorChooser* Browser::OpenColorChooser(
1569 WebContents* web_contents,
1570 SkColor initial_color,
1571 const std::vector<content::ColorSuggestion>& suggestions) {
1572 return chrome::ShowColorChooser(web_contents, initial_color);
1575 void Browser::RunFileChooser(WebContents* web_contents,
1576 const content::FileChooserParams& params) {
1577 FileSelectHelper::RunFileChooser(web_contents, params);
1580 void Browser::EnumerateDirectory(WebContents* web_contents,
1581 int request_id,
1582 const base::FilePath& path) {
1583 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1586 bool Browser::EmbedsFullscreenWidget() const {
1587 #if defined(TOOLKIT_GTK)
1588 return false;
1589 #else
1590 return !CommandLine::ForCurrentProcess()->
1591 HasSwitch(switches::kDisableFullscreenWithinTab);
1592 #endif
1595 void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1596 bool enter_fullscreen) {
1597 fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1598 enter_fullscreen);
1601 bool Browser::IsFullscreenForTabOrPending(
1602 const WebContents* web_contents) const {
1603 return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1606 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1607 const std::string& protocol,
1608 const GURL& url,
1609 const base::string16& title,
1610 bool user_gesture) {
1611 Profile* profile =
1612 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1613 if (profile->IsOffTheRecord())
1614 return;
1616 ProtocolHandler handler =
1617 ProtocolHandler::CreateProtocolHandler(protocol, url, title);
1619 ProtocolHandlerRegistry* registry =
1620 ProtocolHandlerRegistryFactory::GetForProfile(profile);
1621 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1622 return;
1624 TabSpecificContentSettings* tab_content_settings =
1625 TabSpecificContentSettings::FromWebContents(web_contents);
1626 if (!user_gesture && window_) {
1627 tab_content_settings->set_pending_protocol_handler(handler);
1628 tab_content_settings->set_previous_protocol_handler(
1629 registry->GetHandlerFor(handler.protocol()));
1630 window_->GetLocationBar()->UpdateContentSettingsIcons();
1631 return;
1634 // Make sure content-setting icon is turned off in case the page does
1635 // ungestured and gestured RPH calls.
1636 if (window_) {
1637 tab_content_settings->ClearPendingProtocolHandler();
1638 window_->GetLocationBar()->UpdateContentSettingsIcons();
1641 PermissionBubbleManager* bubble_manager =
1642 PermissionBubbleManager::FromWebContents(web_contents);
1643 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1644 bubble_manager->AddRequest(
1645 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1646 url, user_gesture));
1647 } else {
1648 RegisterProtocolHandlerInfoBarDelegate::Create(
1649 InfoBarService::FromWebContents(web_contents), registry, handler);
1653 void Browser::UpdatePreferredSize(WebContents* source,
1654 const gfx::Size& pref_size) {
1655 window_->UpdatePreferredSize(source, pref_size);
1658 void Browser::ResizeDueToAutoResize(WebContents* source,
1659 const gfx::Size& new_size) {
1660 window_->ResizeDueToAutoResize(source, new_size);
1663 void Browser::FindReply(WebContents* web_contents,
1664 int request_id,
1665 int number_of_matches,
1666 const gfx::Rect& selection_rect,
1667 int active_match_ordinal,
1668 bool final_update) {
1669 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1670 if (!find_tab_helper)
1671 return;
1673 find_tab_helper->HandleFindReply(request_id,
1674 number_of_matches,
1675 selection_rect,
1676 active_match_ordinal,
1677 final_update);
1680 void Browser::RequestToLockMouse(WebContents* web_contents,
1681 bool user_gesture,
1682 bool last_unlocked_by_target) {
1683 fullscreen_controller_->RequestToLockMouse(web_contents,
1684 user_gesture,
1685 last_unlocked_by_target);
1688 void Browser::LostMouseLock() {
1689 fullscreen_controller_->LostMouseLock();
1692 void Browser::RequestMediaAccessPermission(
1693 content::WebContents* web_contents,
1694 const content::MediaStreamRequest& request,
1695 const content::MediaResponseCallback& callback) {
1696 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1699 bool Browser::RequestPpapiBrokerPermission(
1700 WebContents* web_contents,
1701 const GURL& url,
1702 const base::FilePath& plugin_path,
1703 const base::Callback<void(bool)>& callback) {
1704 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1705 return true;
1708 gfx::Size Browser::GetSizeForNewRenderView(
1709 const WebContents* web_contents) const {
1710 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1711 // would disappear on non-NTP pages, resulting in a bigger size for the new
1712 // render view.
1713 gfx::Size size = web_contents->GetView()->GetContainerSize();
1714 // Don't change render view size if bookmark bar is currently not detached,
1715 // or there's no pending entry, or navigating to a NTP page.
1716 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1717 return size;
1718 const NavigationEntry* pending_entry =
1719 web_contents->GetController().GetPendingEntry();
1720 if (pending_entry &&
1721 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1722 size.Enlarge(
1723 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1725 return size;
1728 ///////////////////////////////////////////////////////////////////////////////
1729 // Browser, CoreTabHelperDelegate implementation:
1731 void Browser::SwapTabContents(content::WebContents* old_contents,
1732 content::WebContents* new_contents,
1733 bool did_start_load,
1734 bool did_finish_load) {
1735 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1736 DCHECK_NE(TabStripModel::kNoTab, index);
1737 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1740 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1741 return chrome::CanReload(this);
1744 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1745 return chrome::CanSavePage(this);
1748 ///////////////////////////////////////////////////////////////////////////////
1749 // Browser, SearchEngineTabHelperDelegate implementation:
1751 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1752 Profile* profile) {
1753 window()->ConfirmAddSearchProvider(template_url, profile);
1756 ///////////////////////////////////////////////////////////////////////////////
1757 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1759 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1760 bool blocked) {
1761 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1762 if (index == TabStripModel::kNoTab) {
1763 NOTREACHED();
1764 return;
1766 tab_strip_model_->SetTabBlocked(index, blocked);
1767 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1768 web_contents->GetView()->Focus();
1771 web_modal::WebContentsModalDialogHost*
1772 Browser::GetWebContentsModalDialogHost() {
1773 return window_->GetWebContentsModalDialogHost();
1776 ///////////////////////////////////////////////////////////////////////////////
1777 // Browser, BookmarkTabHelperDelegate implementation:
1779 void Browser::URLStarredChanged(content::WebContents* web_contents,
1780 bool starred) {
1781 if (web_contents == tab_strip_model_->GetActiveWebContents())
1782 window_->SetStarredState(starred);
1785 ///////////////////////////////////////////////////////////////////////////////
1786 // Browser, ZoomObserver implementation:
1788 void Browser::OnZoomChanged(content::WebContents* source,
1789 bool can_show_bubble) {
1790 if (source == tab_strip_model_->GetActiveWebContents()) {
1791 // Only show the zoom bubble for zoom changes in the active window.
1792 window_->ZoomChangedForActiveTab(can_show_bubble && window_->IsActive() &&
1793 !is_devtools());
1797 ///////////////////////////////////////////////////////////////////////////////
1798 // Browser, ui::SelectFileDialog::Listener implementation:
1800 void Browser::FileSelected(const base::FilePath& path, int index,
1801 void* params) {
1802 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1805 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1806 int index,
1807 void* params) {
1808 profile_->set_last_selected_directory(file_info.file_path.DirName());
1810 GURL url = net::FilePathToFileURL(file_info.local_path);
1812 #if defined(OS_CHROMEOS)
1813 drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url);
1814 #endif
1816 if (url.is_empty())
1817 return;
1819 OpenURL(OpenURLParams(
1820 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
1823 ///////////////////////////////////////////////////////////////////////////////
1824 // Browser, content::NotificationObserver implementation:
1826 void Browser::Observe(int type,
1827 const content::NotificationSource& source,
1828 const content::NotificationDetails& details) {
1829 switch (type) {
1830 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
1831 chrome::UpdateCommandEnabled(
1832 this,
1833 IDC_BOOKMARK_PAGE,
1834 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1835 chrome::UpdateCommandEnabled(
1836 this,
1837 IDC_BOOKMARK_ALL_TABS,
1838 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1840 if (window()->GetLocationBar())
1841 window()->GetLocationBar()->UpdatePageActions();
1843 const extensions::UnloadedExtensionInfo* extension_info =
1844 content::Details<extensions::UnloadedExtensionInfo>(details).ptr();
1846 // Close any tabs from the unloaded extension, unless it's terminated,
1847 // in which case let the sad tabs remain.
1848 if (extension_info->reason !=
1849 extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
1850 const Extension* extension = extension_info->extension;
1851 // Iterate backwards as we may remove items while iterating.
1852 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1853 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
1854 // Two cases are handled here:
1855 // - The scheme check is for when an extension page is loaded in a
1856 // tab, e.g. chrome-extension://id/page.html.
1857 // - The extension_app check is for apps, which can have non-extension
1858 // schemes, e.g. https://mail.google.com if you have the Gmail app
1859 // installed.
1860 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
1861 web_contents->GetURL().host() == extension->id()) ||
1862 (extensions::TabHelper::FromWebContents(
1863 web_contents)->extension_app() == extension)) {
1864 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
1868 break;
1871 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1872 Profile* profile = content::Source<Profile>(source).ptr();
1873 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1874 window()->GetLocationBar()->InvalidatePageActions();
1875 break;
1878 case chrome::NOTIFICATION_EXTENSION_LOADED:
1879 chrome::UpdateCommandEnabled(
1880 this,
1881 IDC_BOOKMARK_PAGE,
1882 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1883 chrome::UpdateCommandEnabled(
1884 this,
1885 IDC_BOOKMARK_ALL_TABS,
1886 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1887 // fallthrough
1888 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED:
1889 // During window creation on Windows we may end up calling into
1890 // SHAppBarMessage, which internally spawns a nested message loop. This
1891 // makes it possible for us to end up here before window creation has
1892 // completed, at which point window_ is NULL. See 94752 for details.
1893 if (window() && window()->GetLocationBar())
1894 window()->GetLocationBar()->UpdatePageActions();
1895 break;
1897 #if defined(ENABLE_THEMES)
1898 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1899 window()->UserChangedTheme();
1900 break;
1901 #endif
1903 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
1904 WebContents* web_contents = content::Source<WebContents>(source).ptr();
1905 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
1906 LocationBar* location_bar = window()->GetLocationBar();
1907 if (location_bar)
1908 location_bar->UpdateContentSettingsIcons();
1910 break;
1913 default:
1914 NOTREACHED() << "Got a notification we didn't register for.";
1918 ///////////////////////////////////////////////////////////////////////////////
1919 // Browser, Command and state updating (private):
1921 void Browser::OnDevToolsDisabledChanged() {
1922 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
1923 content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1926 ///////////////////////////////////////////////////////////////////////////////
1927 // Browser, UI update coalescing and handling (private):
1929 void Browser::UpdateToolbar(bool should_restore_state) {
1930 window_->UpdateToolbar(should_restore_state ?
1931 tab_strip_model_->GetActiveWebContents() : NULL);
1934 void Browser::ScheduleUIUpdate(const WebContents* source,
1935 unsigned changed_flags) {
1936 DCHECK(source);
1937 int index = tab_strip_model_->GetIndexOfWebContents(source);
1938 DCHECK_NE(TabStripModel::kNoTab, index);
1940 // Do some synchronous updates.
1941 if (changed_flags & content::INVALIDATE_TYPE_URL &&
1942 source == tab_strip_model_->GetActiveWebContents()) {
1943 // Only update the URL for the current tab. Note that we do not update
1944 // the navigation commands since those would have already been updated
1945 // synchronously by NavigationStateChanged.
1946 UpdateToolbar(false);
1947 changed_flags &= ~content::INVALIDATE_TYPE_URL;
1949 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
1950 // Update the loading state synchronously. This is so the throbber will
1951 // immediately start/stop, which gives a more snappy feel. We want to do
1952 // this for any tab so they start & stop quickly.
1953 tab_strip_model_->UpdateWebContentsStateAt(
1954 tab_strip_model_->GetIndexOfWebContents(source),
1955 TabStripModelObserver::LOADING_ONLY);
1956 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
1957 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
1958 // changed_flags.
1961 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
1962 // To correctly calculate whether the title changed while not loading
1963 // we need to process the update synchronously. This state only matters for
1964 // the TabStripModel, so we notify the TabStripModel now and notify others
1965 // asynchronously.
1966 tab_strip_model_->UpdateWebContentsStateAt(
1967 tab_strip_model_->GetIndexOfWebContents(source),
1968 TabStripModelObserver::TITLE_NOT_LOADING);
1971 // If the only updates were synchronously handled above, we're done.
1972 if (changed_flags == 0)
1973 return;
1975 // Save the dirty bits.
1976 scheduled_updates_[source] |= changed_flags;
1978 if (!chrome_updater_factory_.HasWeakPtrs()) {
1979 // No task currently scheduled, start another.
1980 base::MessageLoop::current()->PostDelayedTask(
1981 FROM_HERE,
1982 base::Bind(&Browser::ProcessPendingUIUpdates,
1983 chrome_updater_factory_.GetWeakPtr()),
1984 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
1988 void Browser::ProcessPendingUIUpdates() {
1989 #ifndef NDEBUG
1990 // Validate that all tabs we have pending updates for exist. This is scary
1991 // because the pending list must be kept in sync with any detached or
1992 // deleted tabs.
1993 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
1994 i != scheduled_updates_.end(); ++i) {
1995 bool found = false;
1996 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
1997 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
1998 found = true;
1999 break;
2002 DCHECK(found);
2004 #endif
2006 chrome_updater_factory_.InvalidateWeakPtrs();
2008 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2009 i != scheduled_updates_.end(); ++i) {
2010 // Do not dereference |contents|, it may be out-of-date!
2011 const WebContents* contents = i->first;
2012 unsigned flags = i->second;
2014 if (contents == tab_strip_model_->GetActiveWebContents()) {
2015 // Updates that only matter when the tab is selected go here.
2017 if (flags & content::INVALIDATE_TYPE_PAGE_ACTIONS) {
2018 LocationBar* location_bar = window()->GetLocationBar();
2019 if (location_bar)
2020 location_bar->UpdatePageActions();
2022 // Updating the URL happens synchronously in ScheduleUIUpdate.
2023 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2024 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2025 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2028 if (flags & (content::INVALIDATE_TYPE_TAB |
2029 content::INVALIDATE_TYPE_TITLE)) {
2030 window_->UpdateTitleBar();
2034 // Updates that don't depend upon the selected state go here.
2035 if (flags &
2036 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2037 tab_strip_model_->UpdateWebContentsStateAt(
2038 tab_strip_model_->GetIndexOfWebContents(contents),
2039 TabStripModelObserver::ALL);
2042 // Update the bookmark bar. It may happen that the tab is crashed, and if
2043 // so, the bookmark bar should be hidden.
2044 if (flags & content::INVALIDATE_TYPE_TAB)
2045 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2047 // We don't need to process INVALIDATE_STATE, since that's not visible.
2050 scheduled_updates_.clear();
2053 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2054 if (!contents)
2055 return;
2057 UpdateMap::iterator i = scheduled_updates_.find(contents);
2058 if (i != scheduled_updates_.end())
2059 scheduled_updates_.erase(i);
2062 ///////////////////////////////////////////////////////////////////////////////
2063 // Browser, Getters for UI (private):
2065 StatusBubble* Browser::GetStatusBubble() {
2066 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2067 if (chrome::IsRunningInAppMode())
2068 return NULL;
2070 return window_ ? window_->GetStatusBubble() : NULL;
2073 ///////////////////////////////////////////////////////////////////////////////
2074 // Browser, Session restore functions (private):
2076 void Browser::SyncHistoryWithTabs(int index) {
2077 SessionService* session_service =
2078 SessionServiceFactory::GetForProfileIfExisting(profile());
2079 if (session_service) {
2080 for (int i = index; i < tab_strip_model_->count(); ++i) {
2081 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2082 if (web_contents) {
2083 SessionTabHelper* session_tab_helper =
2084 SessionTabHelper::FromWebContents(web_contents);
2085 session_service->SetTabIndexInWindow(
2086 session_id(), session_tab_helper->session_id(), i);
2087 session_service->SetPinnedState(
2088 session_id(),
2089 session_tab_helper->session_id(),
2090 tab_strip_model_->IsTabPinned(i));
2096 ///////////////////////////////////////////////////////////////////////////////
2097 // Browser, In-progress download termination handling (private):
2099 bool Browser::CanCloseWithInProgressDownloads() {
2100 // If we've prompted, we need to hear from the user before we
2101 // can close.
2102 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2103 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2105 int num_downloads_blocking;
2106 Browser::DownloadClosePreventionType dialog_type =
2107 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2108 if (dialog_type == DOWNLOAD_CLOSE_OK)
2109 return true;
2111 // Closing this window will kill some downloads; prompt to make sure
2112 // that's ok.
2113 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2114 window_->ConfirmBrowserCloseWithPendingDownloads(
2115 num_downloads_blocking,
2116 dialog_type,
2117 false,
2118 base::Bind(&Browser::InProgressDownloadResponse,
2119 weak_factory_.GetWeakPtr()));
2121 // Return false so the browser does not close. We'll close if the user
2122 // confirms in the dialog.
2123 return false;
2126 ///////////////////////////////////////////////////////////////////////////////
2127 // Browser, Assorted utility functions (private):
2129 void Browser::SetAsDelegate(WebContents* web_contents, Browser* delegate) {
2130 // WebContents...
2131 web_contents->SetDelegate(delegate);
2133 // ...and all the helpers.
2134 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2135 WebContentsModalDialogManager::FromWebContents(web_contents)->
2136 SetDelegate(delegate);
2137 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2138 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2139 ZoomController::FromWebContents(web_contents)->set_observer(delegate);
2140 TranslateTabHelper* translate_tab_helper =
2141 TranslateTabHelper::FromWebContents(web_contents);
2142 translate_tab_helper->translate_driver().set_observer(
2143 delegate ? delegate->translate_driver_observer_.get() : NULL);
2146 void Browser::CloseFrame() {
2147 window_->Close();
2150 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2151 int index,
2152 DetachType type) {
2153 if (type == DETACH_TYPE_DETACH) {
2154 // Save the current location bar state, but only if the tab being detached
2155 // is the selected tab. Because saving state can conditionally revert the
2156 // location bar, saving the current tab's location bar state to a
2157 // non-selected tab can corrupt both tabs.
2158 if (contents == tab_strip_model_->GetActiveWebContents()) {
2159 LocationBar* location_bar = window()->GetLocationBar();
2160 if (location_bar)
2161 location_bar->SaveStateToContents(contents);
2164 if (!tab_strip_model_->closing_all())
2165 SyncHistoryWithTabs(0);
2168 SetAsDelegate(contents, NULL);
2169 RemoveScheduledUpdatesFor(contents);
2171 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2172 find_bar_controller_->ChangeWebContents(NULL);
2175 // Stop observing search model changes for this tab.
2176 search_delegate_->OnTabDetached(contents);
2178 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2179 if (interstitial_observers_[i]->web_contents() != contents)
2180 continue;
2182 delete interstitial_observers_[i];
2183 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2184 return;
2188 bool Browser::ShouldShowLocationBar() const {
2189 if (!is_app()) {
2190 // Hide the URL for singleton settings windows.
2191 // TODO(stevenjb): We could avoid this check by setting a Browser
2192 // property for "system" windows, possibly shared with hosted app windows.
2193 // crbug.com/350128.
2194 if (chrome::IsSettingsWindow(this))
2195 return false;
2196 return true;
2199 // Normally apps do not show a location bar.
2200 if (app_type() != APP_TYPE_HOST ||
2201 app_name() == DevToolsWindow::kDevToolsApp ||
2202 !CommandLine::ForCurrentProcess()->HasSwitch(
2203 switches::kEnableStreamlinedHostedApps))
2204 return false;
2206 // If kEnableStreamlinedHostedApps is true, show the locaiton bar for non
2207 // legacy packaged apps.
2208 ExtensionService* service =
2209 extensions::ExtensionSystem::Get(profile_)->extension_service();
2210 const extensions::Extension* extension =
2211 service ? service->GetInstalledExtension(
2212 web_app::GetExtensionIdFromApplicationName(app_name()))
2213 : NULL;
2214 return (!extension || !extension->is_legacy_packaged_app());
2217 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2218 bool check_fullscreen) const {
2219 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2221 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2223 if (is_type_tabbed())
2224 features |= FEATURE_BOOKMARKBAR;
2226 if (!hide_ui_for_fullscreen) {
2227 if (!is_type_tabbed())
2228 features |= FEATURE_TITLEBAR;
2230 if (is_type_tabbed())
2231 features |= FEATURE_TABSTRIP;
2233 if (is_type_tabbed())
2234 features |= FEATURE_TOOLBAR;
2236 if (ShouldShowLocationBar())
2237 features |= FEATURE_LOCATIONBAR;
2239 return !!(features & feature);
2242 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2243 BookmarkBar::State state;
2244 // The bookmark bar is hidden in fullscreen mode, unless on the new tab page.
2245 if (browser_defaults::bookmarks_enabled &&
2246 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) &&
2247 !ShouldHideUIForFullscreen()) {
2248 state = BookmarkBar::SHOW;
2249 } else {
2250 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2251 BookmarkTabHelper* bookmark_tab_helper =
2252 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2253 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2254 state = BookmarkBar::DETACHED;
2255 else
2256 state = BookmarkBar::HIDDEN;
2259 if (state == bookmark_bar_state_)
2260 return;
2262 bookmark_bar_state_ = state;
2264 if (!window_)
2265 return; // This is called from the constructor when window_ is NULL.
2267 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2268 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2269 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2270 // end up querying state once they process the tab switch.
2271 return;
2274 bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2275 window_->BookmarkBarStateChanged(shouldAnimate ?
2276 BookmarkBar::ANIMATE_STATE_CHANGE :
2277 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2280 bool Browser::ShouldHideUIForFullscreen() const {
2281 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2282 // keep the controls in a slide-down panel.
2283 return window_ && window_->ShouldHideUIForFullscreen();
2286 bool Browser::MaybeCreateBackgroundContents(
2287 int route_id,
2288 WebContents* opener_web_contents,
2289 const base::string16& frame_name,
2290 const GURL& target_url,
2291 const std::string& partition_id,
2292 content::SessionStorageNamespace* session_storage_namespace) {
2293 GURL opener_url = opener_web_contents->GetURL();
2294 ExtensionService* extensions_service =
2295 extensions::ExtensionSystem::Get(profile_)->extension_service();
2297 if (!opener_url.is_valid() ||
2298 frame_name.empty() ||
2299 !extensions_service ||
2300 !extensions_service->is_ready())
2301 return false;
2303 // Only hosted apps have web extents, so this ensures that only hosted apps
2304 // can create BackgroundContents. We don't have to check for background
2305 // permission as that is checked in RenderMessageFilter when the CreateWindow
2306 // message is processed.
2307 const Extension* extension =
2308 extensions_service->extensions()->GetHostedAppByURL(opener_url);
2309 if (!extension)
2310 return false;
2312 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2313 BackgroundContentsService* service =
2314 BackgroundContentsServiceFactory::GetForProfile(profile_);
2315 if (!service)
2316 return false;
2318 // Ensure that we're trying to open this from the extension's process.
2319 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2320 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2321 if (!opener_site_instance->GetProcess() ||
2322 !process_map->Contains(
2323 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2324 return false;
2327 // Only allow a single background contents per app.
2328 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2329 BackgroundContents* existing =
2330 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2331 if (existing) {
2332 // For non-scriptable background contents, ignore the request altogether,
2333 // (returning true, so that a regular WebContents isn't created either).
2334 if (!allow_js_access)
2335 return true;
2336 // For scriptable background pages, if one already exists, close it (even
2337 // if it was specified in the manifest).
2338 delete existing;
2341 // If script access is not allowed, create the the background contents in a
2342 // new SiteInstance, so that a separate process is used.
2343 scoped_refptr<content::SiteInstance> site_instance =
2344 allow_js_access ?
2345 opener_site_instance :
2346 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2348 // Passed all the checks, so this should be created as a BackgroundContents.
2349 BackgroundContents* contents =
2350 service->CreateBackgroundContents(site_instance.get(),
2351 route_id,
2352 profile_,
2353 frame_name,
2354 base::ASCIIToUTF16(extension->id()),
2355 partition_id,
2356 session_storage_namespace);
2358 // When a separate process is used, the original renderer cannot access the
2359 // new window later, thus we need to navigate the window now.
2360 if (contents && !allow_js_access) {
2361 contents->web_contents()->GetController().LoadURL(
2362 target_url,
2363 content::Referrer(),
2364 content::PAGE_TRANSITION_LINK,
2365 std::string()); // No extra headers.
2368 return contents != NULL;