Download build archive (if exists) from cloud for given revision and perform bisect.
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob0bb562ca1fa9394f5f1b2d02ecf10bdd29cf15ce
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/browser_command_controller.h"
94 #include "chrome/browser/ui/browser_commands.h"
95 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
96 #include "chrome/browser/ui/browser_content_translate_driver_observer.h"
97 #include "chrome/browser/ui/browser_dialogs.h"
98 #include "chrome/browser/ui/browser_finder.h"
99 #include "chrome/browser/ui/browser_instant_controller.h"
100 #include "chrome/browser/ui/browser_iterator.h"
101 #include "chrome/browser/ui/browser_list.h"
102 #include "chrome/browser/ui/browser_navigator.h"
103 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
104 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
105 #include "chrome/browser/ui/browser_tabstrip.h"
106 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
107 #include "chrome/browser/ui/browser_ui_prefs.h"
108 #include "chrome/browser/ui/browser_window.h"
109 #include "chrome/browser/ui/chrome_pages.h"
110 #include "chrome/browser/ui/chrome_select_file_policy.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/fullscreen/fullscreen_controller.h"
116 #include "chrome/browser/ui/global_error/global_error.h"
117 #include "chrome/browser/ui/global_error/global_error_service.h"
118 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
119 #include "chrome/browser/ui/media_utils.h"
120 #include "chrome/browser/ui/omnibox/location_bar.h"
121 #include "chrome/browser/ui/search/search_delegate.h"
122 #include "chrome/browser/ui/search/search_model.h"
123 #include "chrome/browser/ui/search/search_tab_helper.h"
124 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.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_helpers.h"
130 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
131 #include "chrome/browser/ui/tabs/tab_menu_model.h"
132 #include "chrome/browser/ui/tabs/tab_strip_model.h"
133 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
134 #include "chrome/browser/ui/unload_controller.h"
135 #include "chrome/browser/ui/validation_message_bubble.h"
136 #include "chrome/browser/ui/web_applications/web_app_ui.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,
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 if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers())
450 DCHECK(tab_strip_model_->empty());
452 tab_strip_model_->RemoveObserver(this);
454 // Destroy the BrowserCommandController before removing the browser, so that
455 // it doesn't act on any notifications that are sent as a result of removing
456 // the browser.
457 command_controller_.reset();
458 BrowserList::RemoveBrowser(this);
460 SessionService* session_service =
461 SessionServiceFactory::GetForProfile(profile_);
462 if (session_service)
463 session_service->WindowClosed(session_id_);
465 TabRestoreService* tab_restore_service =
466 TabRestoreServiceFactory::GetForProfile(profile());
467 if (tab_restore_service)
468 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
470 #if !defined(OS_MACOSX)
471 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
472 // We're the last browser window with this profile. We need to nuke the
473 // TabRestoreService, which will start the shutdown of the
474 // NavigationControllers and allow for proper shutdown. If we don't do this
475 // chrome won't shutdown cleanly, and may end up crashing when some
476 // thread tries to use the IO thread (or another thread) that is no longer
477 // valid.
478 // This isn't a valid assumption for Mac OS, as it stays running after
479 // the last browser has closed. The Mac equivalent is in its app
480 // controller.
481 TabRestoreServiceFactory::ResetForProfile(profile_);
483 #endif
485 profile_pref_registrar_.RemoveAll();
487 encoding_auto_detect_.Destroy();
489 // Destroy BrowserExtensionWindowController before the incognito profile
490 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
491 extension_window_controller_.reset();
493 // Destroy BrowserInstantController before the incongnito profile is destroyed
494 // because the InstantController destructor depends on this profile.
495 instant_controller_.reset();
497 if (profile_->IsOffTheRecord() &&
498 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
499 // An incognito profile is no longer needed, this indirectly frees
500 // its cache and cookies once it gets destroyed at the appropriate time.
501 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
504 // There may be pending file dialogs, we need to tell them that we've gone
505 // away so they don't try and call back to us.
506 if (select_file_dialog_.get())
507 select_file_dialog_->ListenerDestroyed();
509 int num_downloads;
510 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
511 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
512 !browser_defaults::kBrowserAliveWithNoWindows) {
513 DownloadService::CancelAllDownloads();
517 ///////////////////////////////////////////////////////////////////////////////
518 // Getters & Setters
520 FindBarController* Browser::GetFindBarController() {
521 if (!find_bar_controller_.get()) {
522 FindBar* find_bar = window_->CreateFindBar();
523 find_bar_controller_.reset(new FindBarController(find_bar));
524 find_bar->SetFindBarController(find_bar_controller_.get());
525 find_bar_controller_->ChangeWebContents(
526 tab_strip_model_->GetActiveWebContents());
527 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
529 return find_bar_controller_.get();
532 bool Browser::HasFindBarController() const {
533 return find_bar_controller_.get() != NULL;
536 bool Browser::is_app() const {
537 return !app_name_.empty();
540 bool Browser::is_devtools() const {
541 return app_name_ == DevToolsWindow::kDevToolsApp;
544 ///////////////////////////////////////////////////////////////////////////////
545 // Browser, State Storage and Retrieval for UI:
547 gfx::Image Browser::GetCurrentPageIcon() const {
548 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
549 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
550 // window during the window's creation (before tabs have been added).
551 FaviconTabHelper* favicon_tab_helper =
552 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
553 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
556 base::string16 Browser::GetWindowTitleForCurrentTab() const {
557 WebContents* contents = tab_strip_model_->GetActiveWebContents();
558 base::string16 title;
560 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
561 // window during the window's creation (before tabs have been added).
562 if (contents) {
563 title = contents->GetTitle();
564 FormatTitleForDisplay(&title);
566 if (title.empty())
567 title = CoreTabHelper::GetDefaultTitle();
569 #if defined(OS_MACOSX)
570 // On Mac, we don't want to suffix the page title with
571 // the application name.
572 return title;
573 #elif defined(USE_ASH)
574 // On Ash, we don't want to suffix the page title with the application name,
575 // but on Windows, where USE_ASH can also be true, we still want the prefix
576 // on desktop.
577 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
578 return title;
579 #endif
580 // Don't append the app name to window titles on app frames and app popups
581 return is_app() ?
582 title :
583 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
586 // static
587 void Browser::FormatTitleForDisplay(base::string16* title) {
588 size_t current_index = 0;
589 size_t match_index;
590 while ((match_index = title->find(L'\n', current_index)) !=
591 base::string16::npos) {
592 title->replace(match_index, 1, base::string16());
593 current_index = match_index;
597 ///////////////////////////////////////////////////////////////////////////////
598 // Browser, OnBeforeUnload handling:
600 bool Browser::ShouldCloseWindow() {
601 if (!CanCloseWithInProgressDownloads())
602 return false;
604 if (IsFastTabUnloadEnabled())
605 return fast_unload_controller_->ShouldCloseWindow();
606 return unload_controller_->ShouldCloseWindow();
609 bool Browser::CallBeforeUnloadHandlers(
610 const base::Callback<void(bool)>& on_close_confirmed) {
611 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
612 if (IsFastTabUnloadEnabled()) {
613 return fast_unload_controller_->CallBeforeUnloadHandlers(
614 on_close_confirmed);
616 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
619 void Browser::ResetBeforeUnloadHandlers() {
620 cancel_download_confirmation_state_ = NOT_PROMPTED;
621 if (IsFastTabUnloadEnabled())
622 fast_unload_controller_->ResetBeforeUnloadHandlers();
623 else
624 unload_controller_->ResetBeforeUnloadHandlers();
627 bool Browser::HasCompletedUnloadProcessing() const {
628 DCHECK(IsFastTabUnloadEnabled());
629 return fast_unload_controller_->HasCompletedUnloadProcessing();
632 bool Browser::IsAttemptingToCloseBrowser() const {
633 if (IsFastTabUnloadEnabled())
634 return fast_unload_controller_->is_attempting_to_close_browser();
635 return unload_controller_->is_attempting_to_close_browser();
638 void Browser::OnWindowClosing() {
639 if (!ShouldCloseWindow())
640 return;
642 // Application should shutdown on last window close if the user is explicitly
643 // trying to quit, or if there is nothing keeping the browser alive (such as
644 // AppController on the Mac, or BackgroundContentsService for background
645 // pages).
646 bool should_quit_if_last_browser =
647 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
649 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this))
650 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
652 // Don't use GetForProfileIfExisting here, we want to force creation of the
653 // session service so that user can restore what was open.
654 SessionService* session_service =
655 SessionServiceFactory::GetForProfile(profile());
656 if (session_service)
657 session_service->WindowClosing(session_id());
659 TabRestoreService* tab_restore_service =
660 TabRestoreServiceFactory::GetForProfile(profile());
662 #if defined(USE_AURA)
663 if (tab_restore_service && is_app() && !is_devtools())
664 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
665 #endif
667 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
668 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
670 // TODO(sky): convert session/tab restore to use notification.
671 content::NotificationService::current()->Notify(
672 chrome::NOTIFICATION_BROWSER_CLOSING,
673 content::Source<Browser>(this),
674 content::NotificationService::NoDetails());
676 if (!IsFastTabUnloadEnabled())
677 tab_strip_model_->CloseAllTabs();
680 ////////////////////////////////////////////////////////////////////////////////
681 // In-progress download termination handling:
683 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
684 if (cancel_downloads) {
685 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
686 chrome::CloseWindow(this);
687 return;
690 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
691 // close again we'll show the warning again.
692 cancel_download_confirmation_state_ = NOT_PROMPTED;
694 // Show the download page so the user can figure-out what downloads are still
695 // in-progress.
696 chrome::ShowDownloads(this);
698 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
699 // prompt every time any tab is closed. http://crbug.com/305516
700 if (IsFastTabUnloadEnabled())
701 fast_unload_controller_->CancelWindowClose();
702 else
703 unload_controller_->CancelWindowClose();
706 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
707 int* num_downloads_blocking) const {
708 DCHECK(num_downloads_blocking);
709 *num_downloads_blocking = 0;
711 // If we're not running a full browser process with a profile manager
712 // (testing), it's ok to close the browser.
713 if (!g_browser_process->profile_manager())
714 return DOWNLOAD_CLOSE_OK;
716 int total_download_count =
717 DownloadService::NonMaliciousDownloadCountAllProfiles();
718 if (total_download_count == 0)
719 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
721 // Figure out how many windows are open total, and associated with this
722 // profile, that are relevant for the ok-to-close decision.
723 int profile_window_count = 0;
724 int total_window_count = 0;
725 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
726 // Don't count this browser window or any other in the process of closing.
727 Browser* const browser = *it;
728 // Window closing may be delayed, and windows that are in the process of
729 // closing don't count against our totals.
730 if (browser == this || browser->IsAttemptingToCloseBrowser())
731 continue;
733 if (it->profile() == profile())
734 profile_window_count++;
735 total_window_count++;
738 // If there aren't any other windows, we're at browser shutdown,
739 // which would cancel all current downloads.
740 if (total_window_count == 0) {
741 *num_downloads_blocking = total_download_count;
742 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
745 // If there aren't any other windows on our profile, and we're an incognito
746 // profile, and there are downloads associated with that profile,
747 // those downloads would be cancelled by our window (-> profile) close.
748 DownloadService* download_service =
749 DownloadServiceFactory::GetForBrowserContext(profile());
750 if ((profile_window_count == 0) &&
751 (download_service->NonMaliciousDownloadCount() > 0) &&
752 profile()->IsOffTheRecord()) {
753 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
754 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
757 // Those are the only conditions under which we will block shutdown.
758 return DOWNLOAD_CLOSE_OK;
761 ////////////////////////////////////////////////////////////////////////////////
762 // Browser, Tab adding/showing functions:
764 void Browser::WindowFullscreenStateChanged() {
765 fullscreen_controller_->WindowFullscreenStateChanged();
766 command_controller_->FullscreenStateChanged();
767 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
770 void Browser::VisibleSSLStateChanged(content::WebContents* web_contents) {
771 // When the current tab's SSL state changes, we need to update the URL
772 // bar to reflect the new state.
773 DCHECK(web_contents);
774 if (tab_strip_model_->GetActiveWebContents() == web_contents)
775 UpdateToolbar(false);
778 void Browser::OnWebContentsInstantSupportDisabled(
779 const content::WebContents* web_contents) {
780 DCHECK(web_contents);
781 if (tab_strip_model_->GetActiveWebContents() == web_contents)
782 UpdateToolbar(false);
785 ///////////////////////////////////////////////////////////////////////////////
786 // Browser, Assorted browser commands:
788 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
789 fullscreen_controller_->ToggleFullscreenModeWithExtension(extension_url);
792 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
793 return SupportsWindowFeatureImpl(feature, true);
796 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
797 return SupportsWindowFeatureImpl(feature, false);
800 void Browser::ToggleEncodingAutoDetect() {
801 content::RecordAction(UserMetricsAction("AutoDetectChange"));
802 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
803 // If "auto detect" is turned on, then any current override encoding
804 // is cleared. This also implicitly performs a reload.
805 // OTOH, if "auto detect" is turned off, we don't change the currently
806 // active encoding.
807 if (encoding_auto_detect_.GetValue()) {
808 WebContents* contents = tab_strip_model_->GetActiveWebContents();
809 if (contents)
810 contents->ResetOverrideEncoding();
814 void Browser::OverrideEncoding(int encoding_id) {
815 content::RecordAction(UserMetricsAction("OverrideEncoding"));
816 const std::string selected_encoding =
817 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
818 WebContents* contents = tab_strip_model_->GetActiveWebContents();
819 if (!selected_encoding.empty() && contents)
820 contents->SetOverrideEncoding(selected_encoding);
821 // Update the list of recently selected encodings.
822 std::string new_selected_encoding_list;
823 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
824 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
825 encoding_id,
826 &new_selected_encoding_list)) {
827 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
828 new_selected_encoding_list);
832 void Browser::OpenFile() {
833 content::RecordAction(UserMetricsAction("OpenFile"));
834 select_file_dialog_ = ui::SelectFileDialog::Create(
835 this, new ChromeSelectFilePolicy(
836 tab_strip_model_->GetActiveWebContents()));
838 const base::FilePath directory = profile_->last_selected_directory();
840 // TODO(beng): figure out how to juggle this.
841 gfx::NativeWindow parent_window = window_->GetNativeWindow();
842 ui::SelectFileDialog::FileTypeInfo file_types;
843 file_types.support_drive = true;
844 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
845 base::string16(),
846 directory,
847 &file_types,
849 base::FilePath::StringType(),
850 parent_window,
851 NULL);
854 void Browser::UpdateDownloadShelfVisibility(bool visible) {
855 if (GetStatusBubble())
856 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
859 ///////////////////////////////////////////////////////////////////////////////
861 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
862 content::PageTransition transition,
863 bool user_initiated) {
864 tab_strip_model_->TabNavigating(contents, transition);
866 bool contents_is_selected =
867 contents == tab_strip_model_->GetActiveWebContents();
868 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
869 // Forcibly reset the location bar if the url is going to change in the
870 // current tab, since otherwise it won't discard any ongoing user edits,
871 // since it doesn't realize this is a user-initiated action.
872 window()->GetLocationBar()->Revert();
875 if (GetStatusBubble())
876 GetStatusBubble()->Hide();
878 // Update the location bar. This is synchronous. We specifically don't
879 // update the load state since the load hasn't started yet and updating it
880 // will put it out of sync with the actual state like whether we're
881 // displaying a favicon, which controls the throbber. If we updated it here,
882 // the throbber will show the default favicon for a split second when
883 // navigating away from the new tab page.
884 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
886 if (contents_is_selected)
887 contents->GetView()->SetInitialFocus();
890 ///////////////////////////////////////////////////////////////////////////////
891 // Browser, PageNavigator implementation:
893 WebContents* Browser::OpenURL(const OpenURLParams& params) {
894 return OpenURLFromTab(NULL, params);
897 ///////////////////////////////////////////////////////////////////////////////
898 // Browser, TabStripModelObserver implementation:
900 void Browser::TabInsertedAt(WebContents* contents,
901 int index,
902 bool foreground) {
903 SetAsDelegate(contents, this);
904 SessionTabHelper* session_tab_helper =
905 SessionTabHelper::FromWebContents(contents);
906 session_tab_helper->SetWindowID(session_id());
908 content::NotificationService::current()->Notify(
909 chrome::NOTIFICATION_TAB_PARENTED,
910 content::Source<content::WebContents>(contents),
911 content::NotificationService::NoDetails());
913 SyncHistoryWithTabs(index);
915 // Make sure the loading state is updated correctly, otherwise the throbber
916 // won't start if the page is loading.
917 LoadingStateChanged(contents);
919 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
921 SessionService* session_service =
922 SessionServiceFactory::GetForProfile(profile_);
923 if (session_service) {
924 session_service->TabInserted(contents);
925 int new_active_index = tab_strip_model_->active_index();
926 if (index < new_active_index)
927 session_service->SetSelectedTabInWindow(session_id(),
928 new_active_index);
932 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
933 WebContents* contents,
934 int index) {
935 fullscreen_controller_->OnTabClosing(contents);
936 SessionService* session_service =
937 SessionServiceFactory::GetForProfile(profile_);
938 if (session_service)
939 session_service->TabClosing(contents);
940 content::NotificationService::current()->Notify(
941 chrome::NOTIFICATION_TAB_CLOSING,
942 content::Source<NavigationController>(&contents->GetController()),
943 content::NotificationService::NoDetails());
945 // Sever the WebContents' connection back to us.
946 SetAsDelegate(contents, NULL);
949 void Browser::TabDetachedAt(WebContents* contents, int index) {
950 // TabDetachedAt is called before TabStripModel has updated the
951 // active index.
952 int old_active_index = tab_strip_model_->active_index();
953 if (index < old_active_index && !tab_strip_model_->closing_all()) {
954 SessionService* session_service =
955 SessionServiceFactory::GetForProfileIfExisting(profile_);
956 if (session_service)
957 session_service->SetSelectedTabInWindow(session_id(),
958 old_active_index - 1);
960 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
963 void Browser::TabDeactivated(WebContents* contents) {
964 fullscreen_controller_->OnTabDeactivated(contents);
965 search_delegate_->OnTabDeactivated(contents);
966 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
968 // Save what the user's currently typing, so it can be restored when we
969 // switch back to this tab.
970 window_->GetLocationBar()->SaveStateToContents(contents);
972 if (instant_controller_)
973 instant_controller_->TabDeactivated(contents);
976 void Browser::ActiveTabChanged(WebContents* old_contents,
977 WebContents* new_contents,
978 int index,
979 int reason) {
980 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
982 // Update the bookmark state, since the BrowserWindow may query it during
983 // OnActiveTabChanged() below.
984 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
986 // Let the BrowserWindow do its handling. On e.g. views this changes the
987 // focused object, which should happen before we update the toolbar below,
988 // since the omnibox expects the correct element to already be focused when it
989 // is updated.
990 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
992 fullscreen_controller_->OnTabDetachedFromView(old_contents);
994 // Discarded tabs always get reloaded.
995 if (tab_strip_model_->IsTabDiscarded(index)) {
996 LOG(WARNING) << "Reloading discarded tab at " << index;
997 static int reload_count = 0;
998 UMA_HISTOGRAM_CUSTOM_COUNTS(
999 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1000 chrome::Reload(this, CURRENT_TAB);
1003 // If we have any update pending, do it now.
1004 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1005 ProcessPendingUIUpdates();
1007 // Propagate the profile to the location bar.
1008 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1010 if (chrome::IsInstantExtendedAPIEnabled())
1011 search_delegate_->OnTabActivated(new_contents);
1013 // Update reload/stop state.
1014 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1016 // Update commands to reflect current state.
1017 command_controller_->TabStateChanged();
1019 // Reset the status bubble.
1020 StatusBubble* status_bubble = GetStatusBubble();
1021 if (status_bubble) {
1022 status_bubble->Hide();
1024 // Show the loading state (if any).
1025 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1026 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1029 if (HasFindBarController()) {
1030 find_bar_controller_->ChangeWebContents(new_contents);
1031 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1034 // Update sessions. Don't force creation of sessions. If sessions doesn't
1035 // exist, the change will be picked up by sessions when created.
1036 SessionService* session_service =
1037 SessionServiceFactory::GetForProfileIfExisting(profile_);
1038 if (session_service && !tab_strip_model_->closing_all()) {
1039 session_service->SetSelectedTabInWindow(session_id(),
1040 tab_strip_model_->active_index());
1043 // This needs to be called after notifying SearchDelegate.
1044 if (instant_controller_)
1045 instant_controller_->ActiveTabChanged();
1047 autofill::TabAutofillManagerDelegate::FromWebContents(new_contents)->
1048 TabActivated();
1049 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1052 void Browser::TabMoved(WebContents* contents,
1053 int from_index,
1054 int to_index) {
1055 DCHECK(from_index >= 0 && to_index >= 0);
1056 // Notify the history service.
1057 SyncHistoryWithTabs(std::min(from_index, to_index));
1060 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1061 WebContents* old_contents,
1062 WebContents* new_contents,
1063 int index) {
1064 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1065 fullscreen_controller_->OnTabClosing(old_contents);
1066 SessionService* session_service =
1067 SessionServiceFactory::GetForProfile(profile_);
1068 if (session_service)
1069 session_service->TabClosing(old_contents);
1070 TabInsertedAt(new_contents,
1071 index,
1072 (index == tab_strip_model_->active_index()));
1074 int entry_count = new_contents->GetController().GetEntryCount();
1075 if (entry_count > 0) {
1076 // Send out notification so that observers are updated appropriately.
1077 new_contents->GetController().NotifyEntryChanged(
1078 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1079 entry_count - 1);
1082 if (session_service) {
1083 // The new_contents may end up with a different navigation stack. Force
1084 // the session service to update itself.
1085 session_service->TabRestored(new_contents,
1086 tab_strip_model_->IsTabPinned(index));
1090 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1091 SessionService* session_service =
1092 SessionServiceFactory::GetForProfileIfExisting(profile());
1093 if (session_service) {
1094 SessionTabHelper* session_tab_helper =
1095 SessionTabHelper::FromWebContents(contents);
1096 session_service->SetPinnedState(session_id(),
1097 session_tab_helper->session_id(),
1098 tab_strip_model_->IsTabPinned(index));
1102 void Browser::TabStripEmpty() {
1103 // Close the frame after we return to the message loop (not immediately,
1104 // otherwise it will destroy this object before the stack has a chance to
1105 // cleanly unwind.)
1106 // Note: This will be called several times if TabStripEmpty is called several
1107 // times. This is because it does not close the window if tabs are
1108 // still present.
1109 base::MessageLoop::current()->PostTask(
1110 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1112 // Instant may have visible WebContents that need to be detached before the
1113 // window system closes.
1114 instant_controller_.reset();
1117 bool Browser::CanOverscrollContent() const {
1118 #if defined(USE_AURA)
1119 bool overscroll_enabled = CommandLine::ForCurrentProcess()->
1120 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "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.
1130 if (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::IsMouseLocked() const {
1196 return fullscreen_controller_->IsMouseLocked();
1199 void Browser::OnWindowDidShow() {
1200 if (window_has_shown_)
1201 return;
1202 window_has_shown_ = true;
1204 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1205 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1206 // Measure the latency from startup till the first browser window becomes
1207 // visible.
1208 static bool is_first_browser_window = true;
1209 if (is_first_browser_window &&
1210 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1211 is_first_browser_window = false;
1212 const base::Time process_creation_time =
1213 base::CurrentProcessInfo::CreationTime();
1215 if (!process_creation_time.is_null()) {
1216 UMA_HISTOGRAM_LONG_TIMES(
1217 "Startup.BrowserWindowDisplay",
1218 base::Time::Now() - process_creation_time);
1221 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1223 // Nothing to do for non-tabbed windows.
1224 if (!is_type_tabbed())
1225 return;
1227 // Show any pending global error bubble.
1228 GlobalErrorService* service =
1229 GlobalErrorServiceFactory::GetForProfile(profile());
1230 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1231 if (error)
1232 error->ShowBubbleView(this);
1235 void Browser::ShowFirstRunBubble() {
1236 window()->GetLocationBar()->ShowFirstRunBubble();
1239 void Browser::ShowDownload(content::DownloadItem* download) {
1240 if (!window())
1241 return;
1243 // If the download occurs in a new tab, and it's not a save page
1244 // download (started before initial navigation completed) close it.
1245 WebContents* source = download->GetWebContents();
1246 if (source && source->GetController().IsInitialNavigation() &&
1247 tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1248 CloseContents(source);
1251 // Some (app downloads) are not supposed to appear on the shelf.
1252 if (!DownloadItemModel(download).ShouldShowInShelf())
1253 return;
1255 // GetDownloadShelf creates the download shelf if it was not yet created.
1256 DownloadShelf* shelf = window()->GetDownloadShelf();
1257 shelf->AddDownload(download);
1260 ///////////////////////////////////////////////////////////////////////////////
1261 // Browser, content::WebContentsDelegate implementation:
1263 WebContents* Browser::OpenURLFromTab(WebContents* source,
1264 const OpenURLParams& params) {
1265 chrome::NavigateParams nav_params(this, params.url, params.transition);
1266 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1267 nav_params.source_contents = source;
1268 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1269 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1270 nav_params.user_gesture = params.user_gesture;
1272 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1273 if (source)
1274 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1276 if (popup_blocker_helper) {
1277 if ((params.disposition == NEW_POPUP ||
1278 params.disposition == NEW_FOREGROUND_TAB ||
1279 params.disposition == NEW_BACKGROUND_TAB ||
1280 params.disposition == NEW_WINDOW) &&
1281 !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1282 switches::kDisablePopupBlocking)) {
1283 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1284 WebWindowFeatures())) {
1285 return NULL;
1290 chrome::Navigate(&nav_params);
1292 return nav_params.target_contents;
1295 void Browser::NavigationStateChanged(const WebContents* source,
1296 unsigned changed_flags) {
1297 // Only update the UI when something visible has changed.
1298 if (changed_flags)
1299 ScheduleUIUpdate(source, changed_flags);
1301 // We can synchronously update commands since they will only change once per
1302 // navigation, so we don't have to worry about flickering. We do, however,
1303 // need to update the command state early on load to always present usable
1304 // actions in the face of slow-to-commit pages.
1305 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1306 content::INVALIDATE_TYPE_LOAD))
1307 command_controller_->TabStateChanged();
1310 void Browser::AddNewContents(WebContents* source,
1311 WebContents* new_contents,
1312 WindowOpenDisposition disposition,
1313 const gfx::Rect& initial_pos,
1314 bool user_gesture,
1315 bool* was_blocked) {
1316 chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1317 user_gesture, was_blocked);
1320 void Browser::ActivateContents(WebContents* contents) {
1321 tab_strip_model_->ActivateTabAt(
1322 tab_strip_model_->GetIndexOfWebContents(contents), false);
1323 window_->Activate();
1326 void Browser::DeactivateContents(WebContents* contents) {
1327 window_->Deactivate();
1330 void Browser::LoadingStateChanged(WebContents* source) {
1331 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1332 window_->UpdateTitleBar();
1334 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1335 if (source == selected_contents) {
1336 bool is_loading = source->IsLoading();
1337 command_controller_->LoadingStateChanged(is_loading, false);
1338 if (GetStatusBubble()) {
1339 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1340 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1345 void Browser::CloseContents(WebContents* source) {
1346 bool can_close_contents;
1347 if (IsFastTabUnloadEnabled())
1348 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1349 else
1350 can_close_contents = unload_controller_->CanCloseContents(source);
1352 if (can_close_contents)
1353 chrome::CloseWebContents(this, source, true);
1356 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1357 if (!IsPopupOrPanel(source)) {
1358 NOTREACHED() << "moving invalid browser type";
1359 return;
1361 window_->SetBounds(pos);
1364 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1365 return is_type_popup();
1368 void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1369 const GURL& url) {
1370 if (!GetStatusBubble())
1371 return;
1373 if (source == tab_strip_model_->GetActiveWebContents()) {
1374 PrefService* prefs = profile_->GetPrefs();
1375 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1379 void Browser::ContentsMouseEvent(
1380 WebContents* source, const gfx::Point& location, bool motion) {
1381 if (!GetStatusBubble())
1382 return;
1384 if (source == tab_strip_model_->GetActiveWebContents()) {
1385 GetStatusBubble()->MouseMoved(location, !motion);
1386 if (!motion)
1387 GetStatusBubble()->SetURL(GURL(), std::string());
1391 void Browser::ContentsZoomChange(bool zoom_in) {
1392 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1395 void Browser::WebContentsFocused(WebContents* contents) {
1396 window_->WebContentsFocused(contents);
1399 bool Browser::TakeFocus(content::WebContents* source,
1400 bool reverse) {
1401 content::NotificationService::current()->Notify(
1402 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1403 content::Source<Browser>(this),
1404 content::NotificationService::NoDetails());
1405 return false;
1408 gfx::Rect Browser::GetRootWindowResizerRect() const {
1409 return window_->GetRootWindowResizerRect();
1412 void Browser::BeforeUnloadFired(WebContents* web_contents,
1413 bool proceed,
1414 bool* proceed_to_fire_unload) {
1415 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1416 proceed, proceed_to_fire_unload))
1417 return;
1419 if (IsFastTabUnloadEnabled()) {
1420 *proceed_to_fire_unload =
1421 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1422 } else {
1423 *proceed_to_fire_unload =
1424 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1428 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1429 const content::NavigationEntry* entry =
1430 source->GetController().GetActiveEntry();
1431 if (entry) {
1432 GURL url = entry->GetURL();
1433 GURL virtual_url = entry->GetVirtualURL();
1434 if ((url.SchemeIs(content::kChromeUIScheme) &&
1435 url.host() == chrome::kChromeUINewTabHost) ||
1436 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1437 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1438 return true;
1442 return chrome::NavEntryIsInstantNTP(source, entry);
1445 void Browser::SetFocusToLocationBar(bool select_all) {
1446 // Two differences between this and FocusLocationBar():
1447 // (1) This doesn't get recorded in user metrics, since it's called
1448 // internally.
1449 // (2) This checks whether the location bar can be focused, and if not, clears
1450 // the focus. FocusLocationBar() is only reached when the location bar is
1451 // focusable, but this may be reached at other times, e.g. while in
1452 // fullscreen mode, where we need to leave focus in a consistent state.
1453 window_->SetFocusToLocationBar(select_all);
1456 int Browser::GetExtraRenderViewHeight() const {
1457 return window_->GetExtraRenderViewHeight();
1460 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1461 DCHECK(source);
1462 chrome::ViewSource(this, source);
1465 void Browser::ViewSourceForFrame(WebContents* source,
1466 const GURL& frame_url,
1467 const content::PageState& frame_page_state) {
1468 DCHECK(source);
1469 chrome::ViewSource(this, source, frame_url, frame_page_state);
1472 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1473 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1474 source);
1477 bool Browser::ShouldCreateWebContents(
1478 WebContents* web_contents,
1479 int route_id,
1480 WindowContainerType window_container_type,
1481 const base::string16& frame_name,
1482 const GURL& target_url,
1483 const std::string& partition_id,
1484 content::SessionStorageNamespace* session_storage_namespace) {
1485 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1486 // If a BackgroundContents is created, suppress the normal WebContents.
1487 return !MaybeCreateBackgroundContents(route_id,
1488 web_contents,
1489 frame_name,
1490 target_url,
1491 partition_id,
1492 session_storage_namespace);
1495 return true;
1498 void Browser::WebContentsCreated(WebContents* source_contents,
1499 int64 source_frame_id,
1500 const base::string16& frame_name,
1501 const GURL& target_url,
1502 WebContents* new_contents) {
1503 // Adopt the WebContents now, so all observers are in place, as the network
1504 // requests for its initial navigation will start immediately. The WebContents
1505 // will later be inserted into this browser using Browser::Navigate via
1506 // AddNewContents.
1507 TabHelpers::AttachTabHelpers(new_contents);
1509 // Notify.
1510 RetargetingDetails details;
1511 details.source_web_contents = source_contents;
1512 details.source_frame_id = source_frame_id;
1513 details.target_url = target_url;
1514 details.target_web_contents = new_contents;
1515 details.not_yet_in_tabstrip = true;
1516 content::NotificationService::current()->Notify(
1517 chrome::NOTIFICATION_RETARGETING,
1518 content::Source<Profile>(profile_),
1519 content::Details<RetargetingDetails>(&details));
1522 void Browser::RendererUnresponsive(WebContents* source) {
1523 // Ignore hangs if a tab is blocked.
1524 int index = tab_strip_model_->GetIndexOfWebContents(source);
1525 DCHECK_NE(TabStripModel::kNoTab, index);
1526 if (tab_strip_model_->IsTabBlocked(index))
1527 return;
1529 chrome::ShowHungRendererDialog(source);
1532 void Browser::RendererResponsive(WebContents* source) {
1533 chrome::HideHungRendererDialog(source);
1536 void Browser::WorkerCrashed(WebContents* source) {
1537 SimpleAlertInfoBarDelegate::Create(
1538 InfoBarService::FromWebContents(source), InfoBarDelegate::kNoIconID,
1539 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1542 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1543 if (web_contents == tab_strip_model_->GetActiveWebContents())
1544 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1547 void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1548 if (web_contents == tab_strip_model_->GetActiveWebContents())
1549 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1552 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1553 return GetJavaScriptDialogManagerInstance();
1556 content::ColorChooser* Browser::OpenColorChooser(
1557 WebContents* web_contents,
1558 SkColor initial_color,
1559 const std::vector<content::ColorSuggestion>& suggestions) {
1560 return chrome::ShowColorChooser(web_contents, initial_color);
1563 void Browser::RunFileChooser(WebContents* web_contents,
1564 const content::FileChooserParams& params) {
1565 FileSelectHelper::RunFileChooser(web_contents, params);
1568 void Browser::EnumerateDirectory(WebContents* web_contents,
1569 int request_id,
1570 const base::FilePath& path) {
1571 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1574 bool Browser::EmbedsFullscreenWidget() const {
1575 #if defined(TOOLKIT_GTK)
1576 return false;
1577 #else
1578 return !CommandLine::ForCurrentProcess()->
1579 HasSwitch(switches::kDisableFullscreenWithinTab);
1580 #endif
1583 void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1584 bool enter_fullscreen) {
1585 fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1586 enter_fullscreen);
1589 bool Browser::IsFullscreenForTabOrPending(
1590 const WebContents* web_contents) const {
1591 return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1594 void Browser::JSOutOfMemory(WebContents* web_contents) {
1595 InfoBarService* infobar_service =
1596 InfoBarService::FromWebContents(web_contents);
1597 if (!infobar_service)
1598 return;
1599 SimpleAlertInfoBarDelegate::Create(
1600 infobar_service, InfoBarDelegate::kNoIconID,
1601 l10n_util::GetStringUTF16(IDS_JS_OUT_OF_MEMORY_PROMPT), true);
1604 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1605 const std::string& protocol,
1606 const GURL& url,
1607 const base::string16& title,
1608 bool user_gesture) {
1609 Profile* profile =
1610 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1611 if (profile->IsOffTheRecord())
1612 return;
1614 ProtocolHandler handler =
1615 ProtocolHandler::CreateProtocolHandler(protocol, url, title);
1617 ProtocolHandlerRegistry* registry =
1618 ProtocolHandlerRegistryFactory::GetForProfile(profile);
1619 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1620 return;
1622 TabSpecificContentSettings* tab_content_settings =
1623 TabSpecificContentSettings::FromWebContents(web_contents);
1624 if (!user_gesture && window_) {
1625 tab_content_settings->set_pending_protocol_handler(handler);
1626 tab_content_settings->set_previous_protocol_handler(
1627 registry->GetHandlerFor(handler.protocol()));
1628 window_->GetLocationBar()->UpdateContentSettingsIcons();
1629 return;
1632 // Make sure content-setting icon is turned off in case the page does
1633 // ungestured and gestured RPH calls.
1634 if (window_) {
1635 tab_content_settings->ClearPendingProtocolHandler();
1636 window_->GetLocationBar()->UpdateContentSettingsIcons();
1639 PermissionBubbleManager* bubble_manager =
1640 PermissionBubbleManager::FromWebContents(web_contents);
1641 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1642 bubble_manager->AddRequest(
1643 new RegisterProtocolHandlerPermissionRequest(registry, handler));
1644 } else {
1645 RegisterProtocolHandlerInfoBarDelegate::Create(
1646 InfoBarService::FromWebContents(web_contents), registry, handler);
1650 void Browser::UpdatePreferredSize(WebContents* source,
1651 const gfx::Size& pref_size) {
1652 window_->UpdatePreferredSize(source, pref_size);
1655 void Browser::ResizeDueToAutoResize(WebContents* source,
1656 const gfx::Size& new_size) {
1657 window_->ResizeDueToAutoResize(source, new_size);
1660 void Browser::FindReply(WebContents* web_contents,
1661 int request_id,
1662 int number_of_matches,
1663 const gfx::Rect& selection_rect,
1664 int active_match_ordinal,
1665 bool final_update) {
1666 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1667 if (!find_tab_helper)
1668 return;
1670 find_tab_helper->HandleFindReply(request_id,
1671 number_of_matches,
1672 selection_rect,
1673 active_match_ordinal,
1674 final_update);
1677 void Browser::RequestToLockMouse(WebContents* web_contents,
1678 bool user_gesture,
1679 bool last_unlocked_by_target) {
1680 fullscreen_controller_->RequestToLockMouse(web_contents,
1681 user_gesture,
1682 last_unlocked_by_target);
1685 void Browser::LostMouseLock() {
1686 fullscreen_controller_->LostMouseLock();
1689 void Browser::RequestMediaAccessPermission(
1690 content::WebContents* web_contents,
1691 const content::MediaStreamRequest& request,
1692 const content::MediaResponseCallback& callback) {
1693 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1696 bool Browser::RequestPpapiBrokerPermission(
1697 WebContents* web_contents,
1698 const GURL& url,
1699 const base::FilePath& plugin_path,
1700 const base::Callback<void(bool)>& callback) {
1701 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1702 return true;
1705 gfx::Size Browser::GetSizeForNewRenderView(
1706 const WebContents* web_contents) const {
1707 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1708 // would disappear on non-NTP pages, resulting in a bigger size for the new
1709 // render view.
1710 gfx::Size size = web_contents->GetView()->GetContainerSize();
1711 // Don't change render view size if bookmark bar is currently not detached,
1712 // or there's no pending entry, or navigating to a NTP page.
1713 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1714 return size;
1715 const NavigationEntry* pending_entry =
1716 web_contents->GetController().GetPendingEntry();
1717 if (pending_entry &&
1718 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1719 size.Enlarge(
1720 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1722 return size;
1725 ///////////////////////////////////////////////////////////////////////////////
1726 // Browser, CoreTabHelperDelegate implementation:
1728 void Browser::SwapTabContents(content::WebContents* old_contents,
1729 content::WebContents* new_contents,
1730 bool did_start_load,
1731 bool did_finish_load) {
1732 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1733 DCHECK_NE(TabStripModel::kNoTab, index);
1734 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1737 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1738 return chrome::CanReload(this);
1741 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1742 return chrome::CanSavePage(this);
1745 ///////////////////////////////////////////////////////////////////////////////
1746 // Browser, SearchEngineTabHelperDelegate implementation:
1748 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1749 Profile* profile) {
1750 window()->ConfirmAddSearchProvider(template_url, profile);
1753 ///////////////////////////////////////////////////////////////////////////////
1754 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1756 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1757 bool blocked) {
1758 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1759 if (index == TabStripModel::kNoTab) {
1760 NOTREACHED();
1761 return;
1763 tab_strip_model_->SetTabBlocked(index, blocked);
1764 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1765 web_contents->GetView()->Focus();
1768 web_modal::WebContentsModalDialogHost*
1769 Browser::GetWebContentsModalDialogHost() {
1770 return window_->GetWebContentsModalDialogHost();
1773 ///////////////////////////////////////////////////////////////////////////////
1774 // Browser, BookmarkTabHelperDelegate implementation:
1776 void Browser::URLStarredChanged(content::WebContents* web_contents,
1777 bool starred) {
1778 if (web_contents == tab_strip_model_->GetActiveWebContents())
1779 window_->SetStarredState(starred);
1782 ///////////////////////////////////////////////////////////////////////////////
1783 // Browser, ZoomObserver implementation:
1785 void Browser::OnZoomChanged(content::WebContents* source,
1786 bool can_show_bubble) {
1787 if (source == tab_strip_model_->GetActiveWebContents()) {
1788 // Only show the zoom bubble for zoom changes in the active window.
1789 window_->ZoomChangedForActiveTab(can_show_bubble && window_->IsActive() &&
1790 !is_devtools());
1794 ///////////////////////////////////////////////////////////////////////////////
1795 // Browser, ui::SelectFileDialog::Listener implementation:
1797 void Browser::FileSelected(const base::FilePath& path, int index,
1798 void* params) {
1799 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1802 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1803 int index,
1804 void* params) {
1805 profile_->set_last_selected_directory(file_info.file_path.DirName());
1807 GURL url = net::FilePathToFileURL(file_info.local_path);
1809 #if defined(OS_CHROMEOS)
1810 drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url);
1811 #endif
1813 if (url.is_empty())
1814 return;
1816 OpenURL(OpenURLParams(
1817 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
1820 ///////////////////////////////////////////////////////////////////////////////
1821 // Browser, content::NotificationObserver implementation:
1823 void Browser::Observe(int type,
1824 const content::NotificationSource& source,
1825 const content::NotificationDetails& details) {
1826 switch (type) {
1827 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
1828 if (window()->GetLocationBar())
1829 window()->GetLocationBar()->UpdatePageActions();
1831 const extensions::UnloadedExtensionInfo* extension_info =
1832 content::Details<extensions::UnloadedExtensionInfo>(details).ptr();
1834 // Close any tabs from the unloaded extension, unless it's terminated,
1835 // in which case let the sad tabs remain.
1836 if (extension_info->reason !=
1837 extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
1838 const Extension* extension = extension_info->extension;
1839 // Iterate backwards as we may remove items while iterating.
1840 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1841 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
1842 // Two cases are handled here:
1843 // - The scheme check is for when an extension page is loaded in a
1844 // tab, e.g. chrome-extension://id/page.html.
1845 // - The extension_app check is for apps, which can have non-extension
1846 // schemes, e.g. https://mail.google.com if you have the Gmail app
1847 // installed.
1848 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
1849 web_contents->GetURL().host() == extension->id()) ||
1850 (extensions::TabHelper::FromWebContents(
1851 web_contents)->extension_app() == extension)) {
1852 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
1856 break;
1859 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1860 Profile* profile = content::Source<Profile>(source).ptr();
1861 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1862 window()->GetLocationBar()->InvalidatePageActions();
1863 break;
1866 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED:
1867 case chrome::NOTIFICATION_EXTENSION_LOADED:
1868 // During window creation on Windows we may end up calling into
1869 // SHAppBarMessage, which internally spawns a nested message loop. This
1870 // makes it possible for us to end up here before window creation has
1871 // completed, at which point window_ is NULL. See 94752 for details.
1872 if (window() && window()->GetLocationBar())
1873 window()->GetLocationBar()->UpdatePageActions();
1874 break;
1876 #if defined(ENABLE_THEMES)
1877 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1878 window()->UserChangedTheme();
1879 break;
1880 #endif
1882 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
1883 WebContents* web_contents = content::Source<WebContents>(source).ptr();
1884 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
1885 LocationBar* location_bar = window()->GetLocationBar();
1886 if (location_bar)
1887 location_bar->UpdateContentSettingsIcons();
1889 break;
1892 default:
1893 NOTREACHED() << "Got a notification we didn't register for.";
1897 ///////////////////////////////////////////////////////////////////////////////
1898 // Browser, Command and state updating (private):
1900 void Browser::OnDevToolsDisabledChanged() {
1901 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
1902 content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1905 ///////////////////////////////////////////////////////////////////////////////
1906 // Browser, UI update coalescing and handling (private):
1908 void Browser::UpdateToolbar(bool should_restore_state) {
1909 window_->UpdateToolbar(should_restore_state ?
1910 tab_strip_model_->GetActiveWebContents() : NULL);
1913 void Browser::ScheduleUIUpdate(const WebContents* source,
1914 unsigned changed_flags) {
1915 DCHECK(source);
1916 int index = tab_strip_model_->GetIndexOfWebContents(source);
1917 DCHECK_NE(TabStripModel::kNoTab, index);
1919 // Do some synchronous updates.
1920 if (changed_flags & content::INVALIDATE_TYPE_URL &&
1921 source == tab_strip_model_->GetActiveWebContents()) {
1922 // Only update the URL for the current tab. Note that we do not update
1923 // the navigation commands since those would have already been updated
1924 // synchronously by NavigationStateChanged.
1925 UpdateToolbar(false);
1926 changed_flags &= ~content::INVALIDATE_TYPE_URL;
1928 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
1929 // Update the loading state synchronously. This is so the throbber will
1930 // immediately start/stop, which gives a more snappy feel. We want to do
1931 // this for any tab so they start & stop quickly.
1932 tab_strip_model_->UpdateWebContentsStateAt(
1933 tab_strip_model_->GetIndexOfWebContents(source),
1934 TabStripModelObserver::LOADING_ONLY);
1935 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
1936 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
1937 // changed_flags.
1940 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
1941 // To correctly calculate whether the title changed while not loading
1942 // we need to process the update synchronously. This state only matters for
1943 // the TabStripModel, so we notify the TabStripModel now and notify others
1944 // asynchronously.
1945 tab_strip_model_->UpdateWebContentsStateAt(
1946 tab_strip_model_->GetIndexOfWebContents(source),
1947 TabStripModelObserver::TITLE_NOT_LOADING);
1950 // If the only updates were synchronously handled above, we're done.
1951 if (changed_flags == 0)
1952 return;
1954 // Save the dirty bits.
1955 scheduled_updates_[source] |= changed_flags;
1957 if (!chrome_updater_factory_.HasWeakPtrs()) {
1958 // No task currently scheduled, start another.
1959 base::MessageLoop::current()->PostDelayedTask(
1960 FROM_HERE,
1961 base::Bind(&Browser::ProcessPendingUIUpdates,
1962 chrome_updater_factory_.GetWeakPtr()),
1963 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
1967 void Browser::ProcessPendingUIUpdates() {
1968 #ifndef NDEBUG
1969 // Validate that all tabs we have pending updates for exist. This is scary
1970 // because the pending list must be kept in sync with any detached or
1971 // deleted tabs.
1972 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
1973 i != scheduled_updates_.end(); ++i) {
1974 bool found = false;
1975 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
1976 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
1977 found = true;
1978 break;
1981 DCHECK(found);
1983 #endif
1985 chrome_updater_factory_.InvalidateWeakPtrs();
1987 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
1988 i != scheduled_updates_.end(); ++i) {
1989 // Do not dereference |contents|, it may be out-of-date!
1990 const WebContents* contents = i->first;
1991 unsigned flags = i->second;
1993 if (contents == tab_strip_model_->GetActiveWebContents()) {
1994 // Updates that only matter when the tab is selected go here.
1996 if (flags & content::INVALIDATE_TYPE_PAGE_ACTIONS) {
1997 LocationBar* location_bar = window()->GetLocationBar();
1998 if (location_bar)
1999 location_bar->UpdatePageActions();
2001 // Updating the URL happens synchronously in ScheduleUIUpdate.
2002 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2003 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2004 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2007 if (flags & (content::INVALIDATE_TYPE_TAB |
2008 content::INVALIDATE_TYPE_TITLE)) {
2009 window_->UpdateTitleBar();
2013 // Updates that don't depend upon the selected state go here.
2014 if (flags &
2015 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2016 tab_strip_model_->UpdateWebContentsStateAt(
2017 tab_strip_model_->GetIndexOfWebContents(contents),
2018 TabStripModelObserver::ALL);
2021 // Update the bookmark bar. It may happen that the tab is crashed, and if
2022 // so, the bookmark bar should be hidden.
2023 if (flags & content::INVALIDATE_TYPE_TAB)
2024 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2026 // We don't need to process INVALIDATE_STATE, since that's not visible.
2029 scheduled_updates_.clear();
2032 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2033 if (!contents)
2034 return;
2036 UpdateMap::iterator i = scheduled_updates_.find(contents);
2037 if (i != scheduled_updates_.end())
2038 scheduled_updates_.erase(i);
2041 ///////////////////////////////////////////////////////////////////////////////
2042 // Browser, Getters for UI (private):
2044 StatusBubble* Browser::GetStatusBubble() {
2045 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2046 if (chrome::IsRunningInAppMode())
2047 return NULL;
2049 return window_ ? window_->GetStatusBubble() : NULL;
2052 ///////////////////////////////////////////////////////////////////////////////
2053 // Browser, Session restore functions (private):
2055 void Browser::SyncHistoryWithTabs(int index) {
2056 SessionService* session_service =
2057 SessionServiceFactory::GetForProfileIfExisting(profile());
2058 if (session_service) {
2059 for (int i = index; i < tab_strip_model_->count(); ++i) {
2060 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2061 if (web_contents) {
2062 SessionTabHelper* session_tab_helper =
2063 SessionTabHelper::FromWebContents(web_contents);
2064 session_service->SetTabIndexInWindow(
2065 session_id(), session_tab_helper->session_id(), i);
2066 session_service->SetPinnedState(
2067 session_id(),
2068 session_tab_helper->session_id(),
2069 tab_strip_model_->IsTabPinned(i));
2075 ///////////////////////////////////////////////////////////////////////////////
2076 // Browser, In-progress download termination handling (private):
2078 bool Browser::CanCloseWithInProgressDownloads() {
2079 // If we've prompted, we need to hear from the user before we
2080 // can close.
2081 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2082 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2084 int num_downloads_blocking;
2085 Browser::DownloadClosePreventionType dialog_type =
2086 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2087 if (dialog_type == DOWNLOAD_CLOSE_OK)
2088 return true;
2090 // Closing this window will kill some downloads; prompt to make sure
2091 // that's ok.
2092 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2093 window_->ConfirmBrowserCloseWithPendingDownloads(
2094 num_downloads_blocking,
2095 dialog_type,
2096 false,
2097 base::Bind(&Browser::InProgressDownloadResponse,
2098 weak_factory_.GetWeakPtr()));
2100 // Return false so the browser does not close. We'll close if the user
2101 // confirms in the dialog.
2102 return false;
2105 ///////////////////////////////////////////////////////////////////////////////
2106 // Browser, Assorted utility functions (private):
2108 void Browser::SetAsDelegate(WebContents* web_contents, Browser* delegate) {
2109 // WebContents...
2110 web_contents->SetDelegate(delegate);
2112 // ...and all the helpers.
2113 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2114 WebContentsModalDialogManager::FromWebContents(web_contents)->
2115 SetDelegate(delegate);
2116 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2117 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2118 ZoomController::FromWebContents(web_contents)->set_observer(delegate);
2119 TranslateTabHelper* translate_tab_helper =
2120 TranslateTabHelper::FromWebContents(web_contents);
2121 translate_tab_helper->translate_driver().set_observer(
2122 delegate ? delegate->translate_driver_observer_.get() : NULL);
2125 void Browser::CloseFrame() {
2126 window_->Close();
2129 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2130 int index,
2131 DetachType type) {
2132 if (type == DETACH_TYPE_DETACH) {
2133 // Save the current location bar state, but only if the tab being detached
2134 // is the selected tab. Because saving state can conditionally revert the
2135 // location bar, saving the current tab's location bar state to a
2136 // non-selected tab can corrupt both tabs.
2137 if (contents == tab_strip_model_->GetActiveWebContents()) {
2138 LocationBar* location_bar = window()->GetLocationBar();
2139 if (location_bar)
2140 location_bar->SaveStateToContents(contents);
2143 if (!tab_strip_model_->closing_all())
2144 SyncHistoryWithTabs(0);
2147 SetAsDelegate(contents, NULL);
2148 RemoveScheduledUpdatesFor(contents);
2150 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2151 find_bar_controller_->ChangeWebContents(NULL);
2154 // Stop observing search model changes for this tab.
2155 search_delegate_->OnTabDetached(contents);
2157 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2158 if (interstitial_observers_[i]->web_contents() != contents)
2159 continue;
2161 delete interstitial_observers_[i];
2162 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2163 return;
2167 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2168 bool check_fullscreen) const {
2169 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2171 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2173 if (is_type_tabbed())
2174 features |= FEATURE_BOOKMARKBAR;
2176 if (!hide_ui_for_fullscreen) {
2177 if (!is_type_tabbed())
2178 features |= FEATURE_TITLEBAR;
2180 if (is_type_tabbed())
2181 features |= FEATURE_TABSTRIP;
2183 if (is_type_tabbed())
2184 features |= FEATURE_TOOLBAR;
2186 ExtensionService* service =
2187 extensions::ExtensionSystem::Get(profile_)->extension_service();
2188 const extensions::Extension* extension =
2189 service ? service->GetInstalledExtension(
2190 web_app::GetExtensionIdFromApplicationName(app_name()))
2191 : NULL;
2193 if (!is_app() || (app_type() == APP_TYPE_HOST &&
2194 app_name() != DevToolsWindow::kDevToolsApp &&
2195 (!extension || !extension->is_legacy_packaged_app()) &&
2196 CommandLine::ForCurrentProcess()->HasSwitch(
2197 switches::kEnableStreamlinedHostedApps))) {
2198 features |= FEATURE_LOCATIONBAR;
2201 return !!(features & feature);
2204 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2205 BookmarkBar::State state;
2206 // The bookmark bar is hidden in fullscreen mode, unless on the new tab page.
2207 if (browser_defaults::bookmarks_enabled &&
2208 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) &&
2209 !ShouldHideUIForFullscreen()) {
2210 state = BookmarkBar::SHOW;
2211 } else {
2212 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2213 BookmarkTabHelper* bookmark_tab_helper =
2214 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2215 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2216 state = BookmarkBar::DETACHED;
2217 else
2218 state = BookmarkBar::HIDDEN;
2221 if (state == bookmark_bar_state_)
2222 return;
2224 bookmark_bar_state_ = state;
2226 if (!window_)
2227 return; // This is called from the constructor when window_ is NULL.
2229 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2230 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2231 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2232 // end up querying state once they process the tab switch.
2233 return;
2236 bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2237 window_->BookmarkBarStateChanged(shouldAnimate ?
2238 BookmarkBar::ANIMATE_STATE_CHANGE :
2239 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2242 bool Browser::ShouldHideUIForFullscreen() const {
2243 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2244 // keep the controls in a slide-down panel.
2245 return window_ && window_->ShouldHideUIForFullscreen();
2248 bool Browser::MaybeCreateBackgroundContents(
2249 int route_id,
2250 WebContents* opener_web_contents,
2251 const base::string16& frame_name,
2252 const GURL& target_url,
2253 const std::string& partition_id,
2254 content::SessionStorageNamespace* session_storage_namespace) {
2255 GURL opener_url = opener_web_contents->GetURL();
2256 ExtensionService* extensions_service =
2257 extensions::ExtensionSystem::Get(profile_)->extension_service();
2259 if (!opener_url.is_valid() ||
2260 frame_name.empty() ||
2261 !extensions_service ||
2262 !extensions_service->is_ready())
2263 return false;
2265 // Only hosted apps have web extents, so this ensures that only hosted apps
2266 // can create BackgroundContents. We don't have to check for background
2267 // permission as that is checked in RenderMessageFilter when the CreateWindow
2268 // message is processed.
2269 const Extension* extension =
2270 extensions_service->extensions()->GetHostedAppByURL(opener_url);
2271 if (!extension)
2272 return false;
2274 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2275 BackgroundContentsService* service =
2276 BackgroundContentsServiceFactory::GetForProfile(profile_);
2277 if (!service)
2278 return false;
2280 // Ensure that we're trying to open this from the extension's process.
2281 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2282 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2283 if (!opener_site_instance->GetProcess() ||
2284 !process_map->Contains(
2285 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2286 return false;
2289 // Only allow a single background contents per app.
2290 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2291 BackgroundContents* existing =
2292 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2293 if (existing) {
2294 // For non-scriptable background contents, ignore the request altogether,
2295 // (returning true, so that a regular WebContents isn't created either).
2296 if (!allow_js_access)
2297 return true;
2298 // For scriptable background pages, if one already exists, close it (even
2299 // if it was specified in the manifest).
2300 delete existing;
2303 // If script access is not allowed, create the the background contents in a
2304 // new SiteInstance, so that a separate process is used.
2305 scoped_refptr<content::SiteInstance> site_instance =
2306 allow_js_access ?
2307 opener_site_instance :
2308 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2310 // Passed all the checks, so this should be created as a BackgroundContents.
2311 BackgroundContents* contents =
2312 service->CreateBackgroundContents(site_instance.get(),
2313 route_id,
2314 profile_,
2315 frame_name,
2316 base::ASCIIToUTF16(extension->id()),
2317 partition_id,
2318 session_storage_namespace);
2320 // When a separate process is used, the original renderer cannot access the
2321 // new window later, thus we need to navigate the window now.
2322 if (contents && !allow_js_access) {
2323 contents->web_contents()->GetController().LoadURL(
2324 target_url,
2325 content::Referrer(),
2326 content::PAGE_TRANSITION_LINK,
2327 std::string()); // No extra headers.
2330 return contents != NULL;