ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob9a80747bb96f8afd131c9b5adc74db70369b1126
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/browser.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #endif // defined(OS_WIN)
12 #include <algorithm>
13 #include <string>
15 #include "base/base_paths.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/process/process_info.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/threading/thread.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "base/time/time.h"
29 #include "chrome/app/chrome_command_ids.h"
30 #include "chrome/browser/app_mode/app_mode_utils.h"
31 #include "chrome/browser/autofill/personal_data_manager_factory.h"
32 #include "chrome/browser/background/background_contents.h"
33 #include "chrome/browser/background/background_contents_service.h"
34 #include "chrome/browser/background/background_contents_service_factory.h"
35 #include "chrome/browser/browser_process.h"
36 #include "chrome/browser/browser_shutdown.h"
37 #include "chrome/browser/browsing_data/browsing_data_helper.h"
38 #include "chrome/browser/browsing_data/browsing_data_remover.h"
39 #include "chrome/browser/character_encoding.h"
40 #include "chrome/browser/chrome_notification_types.h"
41 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
42 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
43 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
44 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
45 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
46 #include "chrome/browser/defaults.h"
47 #include "chrome/browser/devtools/devtools_toggle_action.h"
48 #include "chrome/browser/devtools/devtools_window.h"
49 #include "chrome/browser/download/download_item_model.h"
50 #include "chrome/browser/download/download_service.h"
51 #include "chrome/browser/download/download_service_factory.h"
52 #include "chrome/browser/download/download_shelf.h"
53 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
55 #include "chrome/browser/extensions/browser_extension_window_controller.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_util.h"
58 #include "chrome/browser/extensions/tab_helper.h"
59 #include "chrome/browser/favicon/favicon_tab_helper.h"
60 #include "chrome/browser/file_select_helper.h"
61 #include "chrome/browser/first_run/first_run.h"
62 #include "chrome/browser/history/top_sites_factory.h"
63 #include "chrome/browser/infobars/infobar_service.h"
64 #include "chrome/browser/lifetime/application_lifetime.h"
65 #include "chrome/browser/notifications/notification_ui_manager.h"
66 #include "chrome/browser/pepper_broker_infobar_delegate.h"
67 #include "chrome/browser/prefs/incognito_mode_prefs.h"
68 #include "chrome/browser/profiles/profile.h"
69 #include "chrome/browser/profiles/profile_destroyer.h"
70 #include "chrome/browser/profiles/profile_metrics.h"
71 #include "chrome/browser/repost_form_warning_controller.h"
72 #include "chrome/browser/search/search.h"
73 #include "chrome/browser/sessions/session_service.h"
74 #include "chrome/browser/sessions/session_service_factory.h"
75 #include "chrome/browser/sessions/session_tab_helper.h"
76 #include "chrome/browser/sessions/tab_restore_service.h"
77 #include "chrome/browser/sessions/tab_restore_service_factory.h"
78 #include "chrome/browser/sync/profile_sync_service.h"
79 #include "chrome/browser/sync/profile_sync_service_factory.h"
80 #include "chrome/browser/sync/sync_ui_util.h"
81 #include "chrome/browser/tab_contents/retargeting_details.h"
82 #include "chrome/browser/tab_contents/tab_util.h"
83 #include "chrome/browser/themes/theme_service.h"
84 #include "chrome/browser/themes/theme_service_factory.h"
85 #include "chrome/browser/translate/chrome_translate_client.h"
86 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
87 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
88 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
89 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
90 #include "chrome/browser/ui/browser_command_controller.h"
91 #include "chrome/browser/ui/browser_commands.h"
92 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
93 #include "chrome/browser/ui/browser_dialogs.h"
94 #include "chrome/browser/ui/browser_finder.h"
95 #include "chrome/browser/ui/browser_instant_controller.h"
96 #include "chrome/browser/ui/browser_iterator.h"
97 #include "chrome/browser/ui/browser_list.h"
98 #include "chrome/browser/ui/browser_navigator.h"
99 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
100 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
101 #include "chrome/browser/ui/browser_tabstrip.h"
102 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
103 #include "chrome/browser/ui/browser_ui_prefs.h"
104 #include "chrome/browser/ui/browser_window.h"
105 #include "chrome/browser/ui/chrome_pages.h"
106 #include "chrome/browser/ui/chrome_select_file_policy.h"
107 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
108 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
109 #include "chrome/browser/ui/fast_unload_controller.h"
110 #include "chrome/browser/ui/find_bar/find_bar.h"
111 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
112 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
113 #include "chrome/browser/ui/global_error/global_error.h"
114 #include "chrome/browser/ui/global_error/global_error_service.h"
115 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
116 #include "chrome/browser/ui/location_bar/location_bar.h"
117 #include "chrome/browser/ui/media_utils.h"
118 #include "chrome/browser/ui/search/search_delegate.h"
119 #include "chrome/browser/ui/search/search_model.h"
120 #include "chrome/browser/ui/search/search_tab_helper.h"
121 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
122 #include "chrome/browser/ui/settings_window_manager.h"
123 #include "chrome/browser/ui/singleton_tabs.h"
124 #include "chrome/browser/ui/status_bubble.h"
125 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
126 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
127 #include "chrome/browser/ui/tab_dialogs.h"
128 #include "chrome/browser/ui/tab_helpers.h"
129 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
130 #include "chrome/browser/ui/tabs/tab_menu_model.h"
131 #include "chrome/browser/ui/tabs/tab_strip_model.h"
132 #include "chrome/browser/ui/tabs/tab_strip_model_utils.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/website_settings/permission_bubble_manager.h"
137 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
138 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
139 #include "chrome/browser/ui/window_sizer/window_sizer.h"
140 #include "chrome/browser/upgrade_detector.h"
141 #include "chrome/browser/web_applications/web_app.h"
142 #include "chrome/common/chrome_constants.h"
143 #include "chrome/common/chrome_switches.h"
144 #include "chrome/common/custom_handlers/protocol_handler.h"
145 #include "chrome/common/pref_names.h"
146 #include "chrome/common/profiling.h"
147 #include "chrome/common/search_types.h"
148 #include "chrome/common/url_constants.h"
149 #include "chrome/grit/chromium_strings.h"
150 #include "chrome/grit/generated_resources.h"
151 #include "chrome/grit/locale_settings.h"
152 #include "components/app_modal/javascript_dialog_manager.h"
153 #include "components/bookmarks/browser/bookmark_model.h"
154 #include "components/bookmarks/browser/bookmark_utils.h"
155 #include "components/content_settings/core/browser/host_content_settings_map.h"
156 #include "components/history/core/browser/top_sites.h"
157 #include "components/infobars/core/simple_alert_infobar_delegate.h"
158 #include "components/search/search.h"
159 #include "components/sessions/session_types.h"
160 #include "components/startup_metric_utils/startup_metric_utils.h"
161 #include "components/translate/core/browser/language_state.h"
162 #include "components/ui/zoom/zoom_controller.h"
163 #include "components/web_modal/popup_manager.h"
164 #include "components/web_modal/web_contents_modal_dialog_manager.h"
165 #include "content/public/browser/devtools_agent_host.h"
166 #include "content/public/browser/download_item.h"
167 #include "content/public/browser/download_manager.h"
168 #include "content/public/browser/interstitial_page.h"
169 #include "content/public/browser/invalidate_type.h"
170 #include "content/public/browser/navigation_controller.h"
171 #include "content/public/browser/navigation_entry.h"
172 #include "content/public/browser/notification_details.h"
173 #include "content/public/browser/notification_service.h"
174 #include "content/public/browser/plugin_service.h"
175 #include "content/public/browser/render_process_host.h"
176 #include "content/public/browser/render_view_host.h"
177 #include "content/public/browser/render_widget_host_view.h"
178 #include "content/public/browser/site_instance.h"
179 #include "content/public/browser/user_metrics.h"
180 #include "content/public/browser/web_contents.h"
181 #include "content/public/common/content_switches.h"
182 #include "content/public/common/page_zoom.h"
183 #include "content/public/common/renderer_preferences.h"
184 #include "content/public/common/webplugininfo.h"
185 #include "extensions/browser/extension_prefs.h"
186 #include "extensions/browser/extension_registry.h"
187 #include "extensions/browser/extension_system.h"
188 #include "extensions/common/constants.h"
189 #include "extensions/common/extension.h"
190 #include "extensions/common/manifest_handlers/background_info.h"
191 #include "net/base/filename_util.h"
192 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
193 #include "net/cookies/cookie_monster.h"
194 #include "net/url_request/url_request_context.h"
195 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
196 #include "ui/base/l10n/l10n_util.h"
197 #include "ui/base/window_open_disposition.h"
198 #include "ui/gfx/geometry/point.h"
199 #include "ui/shell_dialogs/selected_file_info.h"
201 #if defined(OS_WIN)
202 #include "base/win/metro.h"
203 #include "chrome/browser/ssl/ssl_error_info.h"
204 #include "chrome/browser/task_manager/task_manager.h"
205 #include "chrome/browser/ui/view_ids.h"
206 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
207 #include "components/browser_watcher/exit_funnel_win.h"
208 #include "ui/base/touch/touch_device.h"
209 #include "ui/base/win/shell.h"
210 #endif // OS_WIN
212 #if defined(OS_CHROMEOS)
213 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
214 #endif
216 #if defined(USE_ASH)
217 #include "ash/ash_switches.h"
218 #endif
220 using base::TimeDelta;
221 using base::UserMetricsAction;
222 using content::NativeWebKeyboardEvent;
223 using content::NavigationController;
224 using content::NavigationEntry;
225 using content::OpenURLParams;
226 using content::PluginService;
227 using content::Referrer;
228 using content::RenderWidgetHostView;
229 using content::SiteInstance;
230 using content::WebContents;
231 using extensions::Extension;
232 using ui::WebDialogDelegate;
233 using web_modal::WebContentsModalDialogManager;
234 using blink::WebWindowFeatures;
236 ///////////////////////////////////////////////////////////////////////////////
238 namespace {
240 // How long we wait before updating the browser chrome while loading a page.
241 const int kUIUpdateCoalescingTimeMS = 200;
243 BrowserWindow* CreateBrowserWindow(Browser* browser) {
244 return BrowserWindow::CreateBrowserWindow(browser);
247 // Is the fast tab unload experiment enabled?
248 bool IsFastTabUnloadEnabled() {
249 return base::CommandLine::ForCurrentProcess()->HasSwitch(
250 switches::kEnableFastUnload);
253 bool IsWebAppFrameEnabled() {
254 return base::CommandLine::ForCurrentProcess()->HasSwitch(
255 switches::kEnableWebAppFrame);
258 } // namespace
260 ////////////////////////////////////////////////////////////////////////////////
261 // Browser, CreateParams:
263 Browser::CreateParams::CreateParams(Profile* profile,
264 chrome::HostDesktopType host_desktop_type)
265 : type(TYPE_TABBED),
266 profile(profile),
267 host_desktop_type(host_desktop_type),
268 trusted_source(false),
269 initial_show_state(ui::SHOW_STATE_DEFAULT),
270 is_session_restore(false),
271 window(NULL) {
274 Browser::CreateParams::CreateParams(Type type,
275 Profile* profile,
276 chrome::HostDesktopType host_desktop_type)
277 : type(type),
278 profile(profile),
279 host_desktop_type(host_desktop_type),
280 trusted_source(false),
281 initial_show_state(ui::SHOW_STATE_DEFAULT),
282 is_session_restore(false),
283 window(NULL) {
286 // static
287 Browser::CreateParams Browser::CreateParams::CreateForApp(
288 const std::string& app_name,
289 bool trusted_source,
290 const gfx::Rect& window_bounds,
291 Profile* profile,
292 chrome::HostDesktopType host_desktop_type) {
293 DCHECK(!app_name.empty());
295 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
296 params.app_name = app_name;
297 params.trusted_source = trusted_source;
298 params.initial_bounds = window_bounds;
300 return params;
303 // static
304 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
305 Profile* profile,
306 chrome::HostDesktopType host_desktop_type) {
307 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
308 params.app_name = DevToolsWindow::kDevToolsApp;
309 params.trusted_source = true;
310 return params;
313 ////////////////////////////////////////////////////////////////////////////////
314 // Browser, InterstitialObserver:
316 class Browser::InterstitialObserver : public content::WebContentsObserver {
317 public:
318 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
319 : WebContentsObserver(web_contents),
320 browser_(browser) {
323 void DidAttachInterstitialPage() override {
324 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
327 void DidDetachInterstitialPage() override {
328 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
331 private:
332 Browser* browser_;
334 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
337 ///////////////////////////////////////////////////////////////////////////////
338 // Browser, Constructors, Creation, Showing:
340 Browser::Browser(const CreateParams& params)
341 : extension_registry_observer_(this),
342 type_(params.type),
343 profile_(params.profile),
344 window_(NULL),
345 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
346 tab_strip_model_(
347 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
348 app_name_(params.app_name),
349 is_trusted_source_(params.trusted_source),
350 cancel_download_confirmation_state_(NOT_PROMPTED),
351 override_bounds_(params.initial_bounds),
352 initial_show_state_(params.initial_show_state),
353 is_session_restore_(params.is_session_restore),
354 host_desktop_type_(
355 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
356 content_setting_bubble_model_delegate_(
357 new BrowserContentSettingBubbleModelDelegate(this)),
358 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
359 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
360 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
361 bookmark_bar_state_(BookmarkBar::HIDDEN),
362 command_controller_(new chrome::BrowserCommandController(this)),
363 window_has_shown_(false),
364 chrome_updater_factory_(this),
365 weak_factory_(this) {
366 // If this causes a crash then a window is being opened using a profile type
367 // that is disallowed by policy. The crash prevents the disabled window type
368 // from opening at all, but the path that triggered it should be fixed.
369 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
370 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
371 << "Only off the record browser may be opened in guest mode";
373 // TODO(jeremy): Move to initializer list once flag is removed.
374 if (IsFastTabUnloadEnabled())
375 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
376 else
377 unload_controller_.reset(new chrome::UnloadController(this));
379 tab_strip_model_->AddObserver(this);
381 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
382 search_model_.reset(new SearchModel());
383 search_delegate_.reset(new SearchDelegate(search_model_.get()));
385 extension_registry_observer_.Add(
386 extensions::ExtensionRegistry::Get(profile_));
387 registrar_.Add(this,
388 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
389 content::NotificationService::AllSources());
390 #if defined(ENABLE_THEMES)
391 registrar_.Add(
392 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
393 content::Source<ThemeService>(
394 ThemeServiceFactory::GetForProfile(profile_)));
395 #endif
396 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
397 content::NotificationService::AllSources());
399 profile_pref_registrar_.Init(profile_->GetPrefs());
400 profile_pref_registrar_.Add(
401 prefs::kDevToolsDisabled,
402 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
403 profile_pref_registrar_.Add(
404 bookmarks::prefs::kShowBookmarkBar,
405 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
406 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
408 BrowserList::AddBrowser(this);
410 // NOTE: These prefs all need to be explicitly destroyed in the destructor
411 // or you'll get a nasty surprise when you run the incognito tests.
412 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
413 profile_->GetPrefs());
415 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
416 instant_controller_.reset(new BrowserInstantController(this));
418 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
420 ProfileMetrics::LogProfileLaunch(profile_);
422 window_ = params.window ? params.window : CreateBrowserWindow(this);
424 // Create the extension window controller before sending notifications.
425 extension_window_controller_.reset(
426 new BrowserExtensionWindowController(this));
428 SessionService* session_service =
429 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
430 if (session_service)
431 session_service->WindowOpened(this);
433 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
434 // replace uses of this with BL's notifications.
435 content::NotificationService::current()->Notify(
436 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
437 content::Source<Browser>(this),
438 content::NotificationService::NoDetails());
440 // TODO(beng): move to ChromeBrowserMain:
441 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
442 #if defined(OS_WIN)
443 // Notify PDM that this is a first run.
444 ImportAutofillDataWin(
445 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
446 #endif // defined(OS_WIN)
449 exclusive_access_manager_.reset(new ExclusiveAccessManager(this));
451 // Must be initialized after window_.
452 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
453 // without a modal dialog host, so that value may be null.
454 popup_manager_.reset(new web_modal::PopupManager(
455 GetWebContentsModalDialogHost()));
458 Browser::~Browser() {
459 // Stop observing notifications before continuing with destruction. Profile
460 // destruction will unload extensions and reentrant calls to Browser:: should
461 // be avoided while it is being torn down.
462 registrar_.RemoveAll();
463 extension_registry_observer_.RemoveAll();
465 // The tab strip should not have any tabs at this point.
466 DCHECK(tab_strip_model_->empty());
467 tab_strip_model_->RemoveObserver(this);
469 // Destroy the BrowserCommandController before removing the browser, so that
470 // it doesn't act on any notifications that are sent as a result of removing
471 // the browser.
472 command_controller_.reset();
473 BrowserList::RemoveBrowser(this);
475 SessionService* session_service =
476 SessionServiceFactory::GetForProfile(profile_);
477 if (session_service)
478 session_service->WindowClosed(session_id_);
480 TabRestoreService* tab_restore_service =
481 TabRestoreServiceFactory::GetForProfile(profile());
482 if (tab_restore_service)
483 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
485 #if !defined(OS_MACOSX)
486 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
487 // We're the last browser window with this profile. We need to nuke the
488 // TabRestoreService, which will start the shutdown of the
489 // NavigationControllers and allow for proper shutdown. If we don't do this
490 // chrome won't shutdown cleanly, and may end up crashing when some
491 // thread tries to use the IO thread (or another thread) that is no longer
492 // valid.
493 // This isn't a valid assumption for Mac OS, as it stays running after
494 // the last browser has closed. The Mac equivalent is in its app
495 // controller.
496 TabRestoreServiceFactory::ResetForProfile(profile_);
498 #endif
500 profile_pref_registrar_.RemoveAll();
502 encoding_auto_detect_.Destroy();
504 // Destroy BrowserExtensionWindowController before the incognito profile
505 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
506 extension_window_controller_.reset();
508 // Destroy BrowserInstantController before the incongnito profile is destroyed
509 // because the InstantController destructor depends on this profile.
510 instant_controller_.reset();
512 if (profile_->IsOffTheRecord() &&
513 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
514 if (profile_->IsGuestSession()) {
515 // ChromeOS handles guest data independently.
516 #if !defined(OS_CHROMEOS)
517 // Clear all browsing data once a Guest Session completes. The Guest
518 // profile has BrowserContextKeyedServices that the Incognito profile
519 // doesn't, so the ProfileDestroyer can't delete it properly.
520 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
521 BrowsingDataRemover* data_remover =
522 BrowsingDataRemover::CreateForUnboundedRange(profile_);
523 data_remover->Remove(BrowsingDataRemover::REMOVE_ALL,
524 BrowsingDataHelper::ALL);
525 // BrowsingDataRemover deletes itself.
526 #endif
527 } else {
528 // An incognito profile is no longer needed, this indirectly frees
529 // its cache and cookies once it gets destroyed at the appropriate time.
530 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
534 // There may be pending file dialogs, we need to tell them that we've gone
535 // away so they don't try and call back to us.
536 if (select_file_dialog_.get())
537 select_file_dialog_->ListenerDestroyed();
539 int num_downloads;
540 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
541 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
542 !browser_defaults::kBrowserAliveWithNoWindows) {
543 DownloadService::CancelAllDownloads();
547 ///////////////////////////////////////////////////////////////////////////////
548 // Getters & Setters
550 FindBarController* Browser::GetFindBarController() {
551 if (!find_bar_controller_.get()) {
552 FindBar* find_bar = window_->CreateFindBar();
553 find_bar_controller_.reset(new FindBarController(find_bar));
554 find_bar->SetFindBarController(find_bar_controller_.get());
555 find_bar_controller_->ChangeWebContents(
556 tab_strip_model_->GetActiveWebContents());
557 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
559 return find_bar_controller_.get();
562 bool Browser::HasFindBarController() const {
563 return find_bar_controller_.get() != NULL;
566 bool Browser::is_app() const {
567 return !app_name_.empty();
570 bool Browser::is_devtools() const {
571 return app_name_ == DevToolsWindow::kDevToolsApp;
574 ///////////////////////////////////////////////////////////////////////////////
575 // Browser, State Storage and Retrieval for UI:
577 gfx::Image Browser::GetCurrentPageIcon() const {
578 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
579 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
580 // window during the window's creation (before tabs have been added).
581 FaviconTabHelper* favicon_tab_helper =
582 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
583 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
586 base::string16 Browser::GetWindowTitleForCurrentTab() const {
587 WebContents* contents = tab_strip_model_->GetActiveWebContents();
588 base::string16 title;
590 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
591 // window during the window's creation (before tabs have been added).
592 if (contents) {
593 // The web app frame uses the host instead of the title.
594 if (ShouldUseWebAppFrame())
595 return base::UTF8ToUTF16(contents->GetURL().host());
597 title = contents->GetTitle();
598 FormatTitleForDisplay(&title);
600 if (title.empty())
601 title = CoreTabHelper::GetDefaultTitle();
603 #if defined(OS_MACOSX)
604 // On Mac, we don't want to suffix the page title with
605 // the application name.
606 return title;
607 #elif defined(USE_ASH)
608 // On Ash, we don't want to suffix the page title with the application name,
609 // but on Windows, where USE_ASH can also be true, we still want the prefix
610 // on desktop.
611 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
612 return title;
613 #endif
614 // Don't append the app name to window titles on app frames and app popups
615 return is_app() ?
616 title :
617 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
620 // static
621 void Browser::FormatTitleForDisplay(base::string16* title) {
622 size_t current_index = 0;
623 size_t match_index;
624 while ((match_index = title->find(L'\n', current_index)) !=
625 base::string16::npos) {
626 title->replace(match_index, 1, base::string16());
627 current_index = match_index;
631 ///////////////////////////////////////////////////////////////////////////////
632 // Browser, OnBeforeUnload handling:
634 bool Browser::ShouldCloseWindow() {
635 if (!CanCloseWithInProgressDownloads())
636 return false;
638 if (IsFastTabUnloadEnabled())
639 return fast_unload_controller_->ShouldCloseWindow();
640 return unload_controller_->ShouldCloseWindow();
643 bool Browser::CallBeforeUnloadHandlers(
644 const base::Callback<void(bool)>& on_close_confirmed) {
645 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
646 if (IsFastTabUnloadEnabled()) {
647 return fast_unload_controller_->CallBeforeUnloadHandlers(
648 on_close_confirmed);
650 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
653 void Browser::ResetBeforeUnloadHandlers() {
654 cancel_download_confirmation_state_ = NOT_PROMPTED;
655 if (IsFastTabUnloadEnabled())
656 fast_unload_controller_->ResetBeforeUnloadHandlers();
657 else
658 unload_controller_->ResetBeforeUnloadHandlers();
661 bool Browser::HasCompletedUnloadProcessing() const {
662 DCHECK(IsFastTabUnloadEnabled());
663 return fast_unload_controller_->HasCompletedUnloadProcessing();
666 bool Browser::IsAttemptingToCloseBrowser() const {
667 if (IsFastTabUnloadEnabled())
668 return fast_unload_controller_->is_attempting_to_close_browser();
669 return unload_controller_->is_attempting_to_close_browser();
672 void Browser::OnWindowClosing() {
673 if (!ShouldCloseWindow())
674 return;
676 // Application should shutdown on last window close if the user is explicitly
677 // trying to quit, or if there is nothing keeping the browser alive (such as
678 // AppController on the Mac, or BackgroundContentsService for background
679 // pages).
680 bool should_quit_if_last_browser =
681 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
683 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this)) {
684 #if defined(OS_WIN)
685 browser_watcher::ExitFunnel::RecordSingleEvent(
686 chrome::kBrowserExitCodesRegistryPath, L"LastWindowClose");
687 #endif
688 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
691 // Don't use GetForProfileIfExisting here, we want to force creation of the
692 // session service so that user can restore what was open.
693 SessionService* session_service =
694 SessionServiceFactory::GetForProfile(profile());
695 if (session_service)
696 session_service->WindowClosing(session_id());
698 TabRestoreService* tab_restore_service =
699 TabRestoreServiceFactory::GetForProfile(profile());
701 #if defined(USE_AURA)
702 if (tab_restore_service && is_app() && !is_devtools())
703 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
704 #endif
706 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
707 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
709 // TODO(sky): convert session/tab restore to use notification.
710 content::NotificationService::current()->Notify(
711 chrome::NOTIFICATION_BROWSER_CLOSING,
712 content::Source<Browser>(this),
713 content::NotificationService::NoDetails());
715 if (!IsFastTabUnloadEnabled())
716 tab_strip_model_->CloseAllTabs();
719 ////////////////////////////////////////////////////////////////////////////////
720 // In-progress download termination handling:
722 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
723 if (cancel_downloads) {
724 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
725 chrome::CloseWindow(this);
726 return;
729 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
730 // close again we'll show the warning again.
731 cancel_download_confirmation_state_ = NOT_PROMPTED;
733 // Show the download page so the user can figure-out what downloads are still
734 // in-progress.
735 chrome::ShowDownloads(this);
737 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
738 // prompt every time any tab is closed. http://crbug.com/305516
739 if (IsFastTabUnloadEnabled())
740 fast_unload_controller_->CancelWindowClose();
741 else
742 unload_controller_->CancelWindowClose();
745 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
746 int* num_downloads_blocking) const {
747 DCHECK(num_downloads_blocking);
748 *num_downloads_blocking = 0;
750 // If we're not running a full browser process with a profile manager
751 // (testing), it's ok to close the browser.
752 if (!g_browser_process->profile_manager())
753 return DOWNLOAD_CLOSE_OK;
755 int total_download_count =
756 DownloadService::NonMaliciousDownloadCountAllProfiles();
757 if (total_download_count == 0)
758 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
760 // Figure out how many windows are open total, and associated with this
761 // profile, that are relevant for the ok-to-close decision.
762 int profile_window_count = 0;
763 int total_window_count = 0;
764 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
765 // Don't count this browser window or any other in the process of closing.
766 Browser* const browser = *it;
767 // Window closing may be delayed, and windows that are in the process of
768 // closing don't count against our totals.
769 if (browser == this || browser->IsAttemptingToCloseBrowser())
770 continue;
772 if (it->profile() == profile())
773 profile_window_count++;
774 total_window_count++;
777 // If there aren't any other windows, we're at browser shutdown,
778 // which would cancel all current downloads.
779 if (total_window_count == 0) {
780 *num_downloads_blocking = total_download_count;
781 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
784 // If there aren't any other windows on our profile, and we're an incognito
785 // profile, and there are downloads associated with that profile,
786 // those downloads would be cancelled by our window (-> profile) close.
787 DownloadService* download_service =
788 DownloadServiceFactory::GetForBrowserContext(profile());
789 if ((profile_window_count == 0) &&
790 (download_service->NonMaliciousDownloadCount() > 0) &&
791 profile()->IsOffTheRecord()) {
792 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
793 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
796 // Those are the only conditions under which we will block shutdown.
797 return DOWNLOAD_CLOSE_OK;
800 ////////////////////////////////////////////////////////////////////////////////
801 // Browser, Tab adding/showing functions:
803 void Browser::WindowFullscreenStateChanged() {
804 exclusive_access_manager_->fullscreen_controller()
805 ->WindowFullscreenStateChanged();
806 command_controller_->FullscreenStateChanged();
807 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
810 ///////////////////////////////////////////////////////////////////////////////
811 // Browser, Assorted browser commands:
813 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
814 exclusive_access_manager_->fullscreen_controller()
815 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
818 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
819 return SupportsWindowFeatureImpl(feature, true);
822 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
823 return SupportsWindowFeatureImpl(feature, false);
826 void Browser::ToggleEncodingAutoDetect() {
827 content::RecordAction(UserMetricsAction("AutoDetectChange"));
828 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
829 // If "auto detect" is turned on, then any current override encoding
830 // is cleared. This also implicitly performs a reload.
831 // OTOH, if "auto detect" is turned off, we don't change the currently
832 // active encoding.
833 if (encoding_auto_detect_.GetValue()) {
834 WebContents* contents = tab_strip_model_->GetActiveWebContents();
835 if (contents)
836 contents->ResetOverrideEncoding();
840 void Browser::OverrideEncoding(int encoding_id) {
841 content::RecordAction(UserMetricsAction("OverrideEncoding"));
842 const std::string selected_encoding =
843 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
844 WebContents* contents = tab_strip_model_->GetActiveWebContents();
845 if (!selected_encoding.empty() && contents)
846 contents->SetOverrideEncoding(selected_encoding);
847 // Update the list of recently selected encodings.
848 std::string new_selected_encoding_list;
849 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
850 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
851 encoding_id,
852 &new_selected_encoding_list)) {
853 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
854 new_selected_encoding_list);
858 void Browser::OpenFile() {
859 content::RecordAction(UserMetricsAction("OpenFile"));
860 select_file_dialog_ = ui::SelectFileDialog::Create(
861 this, new ChromeSelectFilePolicy(
862 tab_strip_model_->GetActiveWebContents()));
864 const base::FilePath directory = profile_->last_selected_directory();
866 // TODO(beng): figure out how to juggle this.
867 gfx::NativeWindow parent_window = window_->GetNativeWindow();
868 ui::SelectFileDialog::FileTypeInfo file_types;
869 file_types.support_drive = true;
870 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
871 base::string16(),
872 directory,
873 &file_types,
875 base::FilePath::StringType(),
876 parent_window,
877 NULL);
880 void Browser::UpdateDownloadShelfVisibility(bool visible) {
881 if (GetStatusBubble())
882 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
885 ///////////////////////////////////////////////////////////////////////////////
887 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
888 ui::PageTransition transition,
889 bool user_initiated) {
890 tab_strip_model_->TabNavigating(contents, transition);
892 bool contents_is_selected =
893 contents == tab_strip_model_->GetActiveWebContents();
894 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
895 // Forcibly reset the location bar if the url is going to change in the
896 // current tab, since otherwise it won't discard any ongoing user edits,
897 // since it doesn't realize this is a user-initiated action.
898 window()->GetLocationBar()->Revert();
901 if (GetStatusBubble())
902 GetStatusBubble()->Hide();
904 // Update the location bar. This is synchronous. We specifically don't
905 // update the load state since the load hasn't started yet and updating it
906 // will put it out of sync with the actual state like whether we're
907 // displaying a favicon, which controls the throbber. If we updated it here,
908 // the throbber will show the default favicon for a split second when
909 // navigating away from the new tab page.
910 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
912 if (contents_is_selected)
913 contents->SetInitialFocus();
916 ///////////////////////////////////////////////////////////////////////////////
917 // Browser, PageNavigator implementation:
919 WebContents* Browser::OpenURL(const OpenURLParams& params) {
920 return OpenURLFromTab(NULL, params);
923 ///////////////////////////////////////////////////////////////////////////////
924 // Browser, TabStripModelObserver implementation:
926 void Browser::TabInsertedAt(WebContents* contents,
927 int index,
928 bool foreground) {
929 SetAsDelegate(contents, true);
931 if (popup_manager_)
932 popup_manager_->RegisterWith(contents);
934 SessionTabHelper* session_tab_helper =
935 SessionTabHelper::FromWebContents(contents);
936 session_tab_helper->SetWindowID(session_id());
938 content::NotificationService::current()->Notify(
939 chrome::NOTIFICATION_TAB_PARENTED,
940 content::Source<content::WebContents>(contents),
941 content::NotificationService::NoDetails());
943 SyncHistoryWithTabs(index);
945 // Make sure the loading state is updated correctly, otherwise the throbber
946 // won't start if the page is loading.
947 LoadingStateChanged(contents, true);
949 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
951 SessionService* session_service =
952 SessionServiceFactory::GetForProfile(profile_);
953 if (session_service) {
954 session_service->TabInserted(contents);
955 int new_active_index = tab_strip_model_->active_index();
956 if (index < new_active_index)
957 session_service->SetSelectedTabInWindow(session_id(),
958 new_active_index);
962 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
963 WebContents* contents,
964 int index) {
965 exclusive_access_manager_->OnTabClosing(contents);
966 SessionService* session_service =
967 SessionServiceFactory::GetForProfile(profile_);
968 if (session_service)
969 session_service->TabClosing(contents);
970 content::NotificationService::current()->Notify(
971 chrome::NOTIFICATION_TAB_CLOSING,
972 content::Source<NavigationController>(&contents->GetController()),
973 content::NotificationService::NoDetails());
975 if (popup_manager_)
976 popup_manager_->UnregisterWith(contents);
978 // Sever the WebContents' connection back to us.
979 SetAsDelegate(contents, false);
982 void Browser::TabDetachedAt(WebContents* contents, int index) {
983 // TabDetachedAt is called before TabStripModel has updated the
984 // active index.
985 int old_active_index = tab_strip_model_->active_index();
986 if (index < old_active_index && !tab_strip_model_->closing_all()) {
987 SessionService* session_service =
988 SessionServiceFactory::GetForProfileIfExisting(profile_);
989 if (session_service)
990 session_service->SetSelectedTabInWindow(session_id(),
991 old_active_index - 1);
994 if (popup_manager_)
995 popup_manager_->UnregisterWith(contents);
997 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1000 void Browser::TabDeactivated(WebContents* contents) {
1001 exclusive_access_manager_->OnTabDeactivated(contents);
1002 search_delegate_->OnTabDeactivated(contents);
1003 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
1005 // Save what the user's currently typing, so it can be restored when we
1006 // switch back to this tab.
1007 window_->GetLocationBar()->SaveStateToContents(contents);
1009 if (instant_controller_)
1010 instant_controller_->TabDeactivated(contents);
1013 void Browser::ActiveTabChanged(WebContents* old_contents,
1014 WebContents* new_contents,
1015 int index,
1016 int reason) {
1017 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1019 // Update the bookmark state, since the BrowserWindow may query it during
1020 // OnActiveTabChanged() below.
1021 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1023 // Let the BrowserWindow do its handling. On e.g. views this changes the
1024 // focused object, which should happen before we update the toolbar below,
1025 // since the omnibox expects the correct element to already be focused when it
1026 // is updated.
1027 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1029 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
1031 // Discarded tabs always get reloaded.
1032 if (tab_strip_model_->IsTabDiscarded(index)) {
1033 LOG(WARNING) << "Reloading discarded tab at " << index;
1034 static int reload_count = 0;
1035 UMA_HISTOGRAM_CUSTOM_COUNTS(
1036 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1037 chrome::Reload(this, CURRENT_TAB);
1040 // If we have any update pending, do it now.
1041 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1042 ProcessPendingUIUpdates();
1044 // Propagate the profile to the location bar.
1045 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1047 if (chrome::IsInstantExtendedAPIEnabled())
1048 search_delegate_->OnTabActivated(new_contents);
1050 // Update reload/stop state.
1051 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1053 // Update commands to reflect current state.
1054 command_controller_->TabStateChanged();
1056 // Reset the status bubble.
1057 StatusBubble* status_bubble = GetStatusBubble();
1058 if (status_bubble) {
1059 status_bubble->Hide();
1061 // Show the loading state (if any).
1062 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1063 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1066 if (HasFindBarController()) {
1067 find_bar_controller_->ChangeWebContents(new_contents);
1068 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1071 // Update sessions. Don't force creation of sessions. If sessions doesn't
1072 // exist, the change will be picked up by sessions when created.
1073 SessionService* session_service =
1074 SessionServiceFactory::GetForProfileIfExisting(profile_);
1075 if (session_service && !tab_strip_model_->closing_all()) {
1076 session_service->SetSelectedTabInWindow(session_id(),
1077 tab_strip_model_->active_index());
1080 // This needs to be called after notifying SearchDelegate.
1081 if (instant_controller_)
1082 instant_controller_->ActiveTabChanged();
1084 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1085 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1088 void Browser::TabMoved(WebContents* contents,
1089 int from_index,
1090 int to_index) {
1091 DCHECK(from_index >= 0 && to_index >= 0);
1092 // Notify the history service.
1093 SyncHistoryWithTabs(std::min(from_index, to_index));
1096 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1097 WebContents* old_contents,
1098 WebContents* new_contents,
1099 int index) {
1100 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1101 exclusive_access_manager_->OnTabClosing(old_contents);
1102 SessionService* session_service =
1103 SessionServiceFactory::GetForProfile(profile_);
1104 if (session_service)
1105 session_service->TabClosing(old_contents);
1106 TabInsertedAt(new_contents,
1107 index,
1108 (index == tab_strip_model_->active_index()));
1110 int entry_count = new_contents->GetController().GetEntryCount();
1111 if (entry_count > 0) {
1112 // Send out notification so that observers are updated appropriately.
1113 new_contents->GetController().NotifyEntryChanged(
1114 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1115 entry_count - 1);
1118 if (session_service) {
1119 // The new_contents may end up with a different navigation stack. Force
1120 // the session service to update itself.
1121 session_service->TabRestored(new_contents,
1122 tab_strip_model_->IsTabPinned(index));
1126 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1127 SessionService* session_service =
1128 SessionServiceFactory::GetForProfileIfExisting(profile());
1129 if (session_service) {
1130 SessionTabHelper* session_tab_helper =
1131 SessionTabHelper::FromWebContents(contents);
1132 session_service->SetPinnedState(session_id(),
1133 session_tab_helper->session_id(),
1134 tab_strip_model_->IsTabPinned(index));
1138 void Browser::TabStripEmpty() {
1139 // Close the frame after we return to the message loop (not immediately,
1140 // otherwise it will destroy this object before the stack has a chance to
1141 // cleanly unwind.)
1142 // Note: This will be called several times if TabStripEmpty is called several
1143 // times. This is because it does not close the window if tabs are
1144 // still present.
1145 base::MessageLoop::current()->PostTask(
1146 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1148 // Instant may have visible WebContents that need to be detached before the
1149 // window system closes.
1150 instant_controller_.reset();
1153 bool Browser::CanOverscrollContent() const {
1154 #if defined(OS_WIN)
1155 // Don't enable overscroll on Windows machines unless they have a touch
1156 // screen as these machines typically don't have a touchpad capable of
1157 // horizontal scrolling. We are purposefully biased towards "no" here,
1158 // so that we don't waste resources capturing screenshots for horizontal
1159 // overscroll navigation unnecessarily.
1160 bool allow_overscroll = ui::IsTouchDevicePresent();
1161 #elif defined(USE_AURA)
1162 bool allow_overscroll = true;
1163 #else
1164 bool allow_overscroll = false;
1165 #endif
1167 if (!allow_overscroll)
1168 return false;
1170 const std::string value =
1171 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1172 switches::kOverscrollHistoryNavigation);
1173 bool overscroll_enabled = value != "0";
1174 if (!overscroll_enabled)
1175 return false;
1176 if (is_app() || is_devtools() || !is_type_tabbed())
1177 return false;
1179 // The detached bookmark bar has appearance of floating above the
1180 // web-contents. This does not play nicely with overscroll navigation
1181 // gestures. So disable overscroll navigation when the bookmark bar is in the
1182 // detached state and the overscroll effect moves the layers.
1183 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1184 return false;
1185 return true;
1188 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1189 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1190 // other pages have committed.
1191 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1192 if (!profile || !source->GetController().GetLastCommittedEntry())
1193 return false;
1194 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1195 return chrome::IsNTPURL(committed_url, profile);
1198 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1199 const NativeWebKeyboardEvent& event,
1200 bool* is_keyboard_shortcut) {
1201 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1202 // TODO(koz): Write a test for this http://crbug.com/100441.
1203 if (event.windowsKeyCode == 27 &&
1204 exclusive_access_manager_->HandleUserPressedEscape()) {
1205 return true;
1207 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1210 void Browser::HandleKeyboardEvent(content::WebContents* source,
1211 const NativeWebKeyboardEvent& event) {
1212 DevToolsWindow* devtools_window =
1213 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1214 bool handled = false;
1215 if (devtools_window)
1216 handled = devtools_window->ForwardKeyboardEvent(event);
1218 if (!handled)
1219 window()->HandleKeyboardEvent(event);
1222 bool Browser::TabsNeedBeforeUnloadFired() {
1223 if (IsFastTabUnloadEnabled())
1224 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1225 return unload_controller_->TabsNeedBeforeUnloadFired();
1228 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1229 const gfx::Rect& anchor_in_root_view,
1230 const base::string16& main_text,
1231 const base::string16& sub_text) {
1232 validation_message_bubble_ =
1233 TabDialogs::FromWebContents(web_contents)
1234 ->ShowValidationMessage(anchor_in_root_view, main_text, sub_text);
1237 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1238 validation_message_bubble_.reset();
1241 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1242 const gfx::Rect& anchor_in_root_view) {
1243 if (!validation_message_bubble_)
1244 return;
1245 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1246 if (rwhv) {
1247 validation_message_bubble_->SetPositionRelativeToAnchor(
1248 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1252 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1253 const blink::WebGestureEvent& event) {
1254 // Disable pinch zooming in undocked dev tools window due to poor UX.
1255 if (app_name() == DevToolsWindow::kDevToolsApp)
1256 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1257 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1258 event.type == blink::WebGestureEvent::GesturePinchEnd;
1260 return false;
1263 bool Browser::CanDragEnter(content::WebContents* source,
1264 const content::DropData& data,
1265 blink::WebDragOperationsMask operations_allowed) {
1266 // Disallow drag-and-drop navigation for Settings windows which do not support
1267 // external navigation.
1268 if ((operations_allowed & blink::WebDragOperationLink) &&
1269 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1270 return false;
1272 return true;
1275 bool Browser::IsMouseLocked() const {
1276 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1279 void Browser::OnWindowDidShow() {
1280 if (window_has_shown_)
1281 return;
1282 window_has_shown_ = true;
1284 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1285 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1286 // Measure the latency from startup till the first browser window becomes
1287 // visible.
1288 static bool is_first_browser_window = true;
1289 if (is_first_browser_window &&
1290 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1291 is_first_browser_window = false;
1292 const base::Time process_creation_time =
1293 base::CurrentProcessInfo::CreationTime();
1295 if (!process_creation_time.is_null()) {
1296 UMA_HISTOGRAM_LONG_TIMES(
1297 "Startup.BrowserWindowDisplay",
1298 base::Time::Now() - process_creation_time);
1301 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1303 // Nothing to do for non-tabbed windows.
1304 if (!is_type_tabbed())
1305 return;
1307 // Show any pending global error bubble.
1308 GlobalErrorService* service =
1309 GlobalErrorServiceFactory::GetForProfile(profile());
1310 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1311 if (error)
1312 error->ShowBubbleView(this);
1315 void Browser::ShowFirstRunBubble() {
1316 window()->GetLocationBar()->ShowFirstRunBubble();
1319 void Browser::ShowDownload(content::DownloadItem* download) {
1320 if (!window())
1321 return;
1323 // If the download occurs in a new tab, and it's not a save page
1324 // download (started before initial navigation completed) close it.
1325 // Avoid calling CloseContents if the tab is not in this browser's tab strip
1326 // model; this can happen if the download was initiated by something internal
1327 // to Chrome, such as by the app list.
1328 WebContents* source = download->GetWebContents();
1329 if (source && source->GetController().IsInitialNavigation() &&
1330 tab_strip_model_->count() > 1 &&
1331 tab_strip_model_->GetIndexOfWebContents(source) !=
1332 TabStripModel::kNoTab &&
1333 !download->IsSavePackageDownload()) {
1334 CloseContents(source);
1337 // Some (app downloads) are not supposed to appear on the shelf.
1338 if (!DownloadItemModel(download).ShouldShowInShelf())
1339 return;
1341 // GetDownloadShelf creates the download shelf if it was not yet created.
1342 window()->GetDownloadShelf()->AddDownload(download);
1345 ///////////////////////////////////////////////////////////////////////////////
1346 // Browser, content::WebContentsDelegate implementation:
1348 WebContents* Browser::OpenURLFromTab(WebContents* source,
1349 const OpenURLParams& params) {
1350 if (is_devtools()) {
1351 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1352 DCHECK(window);
1353 return window->OpenURLFromTab(source, params);
1356 chrome::NavigateParams nav_params(this, params.url, params.transition);
1357 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1358 nav_params.source_contents = source;
1359 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1360 if (params.user_gesture)
1361 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1362 nav_params.user_gesture = params.user_gesture;
1364 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1365 if (source)
1366 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1368 if (popup_blocker_helper) {
1369 if ((params.disposition == NEW_POPUP ||
1370 params.disposition == NEW_FOREGROUND_TAB ||
1371 params.disposition == NEW_BACKGROUND_TAB ||
1372 params.disposition == NEW_WINDOW) &&
1373 !params.user_gesture &&
1374 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1375 switches::kDisablePopupBlocking)) {
1376 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1377 WebWindowFeatures())) {
1378 return NULL;
1383 chrome::Navigate(&nav_params);
1385 return nav_params.target_contents;
1388 void Browser::NavigationStateChanged(WebContents* source,
1389 content::InvalidateTypes changed_flags) {
1390 // Only update the UI when something visible has changed.
1391 if (changed_flags)
1392 ScheduleUIUpdate(source, changed_flags);
1394 // We can synchronously update commands since they will only change once per
1395 // navigation, so we don't have to worry about flickering. We do, however,
1396 // need to update the command state early on load to always present usable
1397 // actions in the face of slow-to-commit pages.
1398 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1399 content::INVALIDATE_TYPE_LOAD))
1400 command_controller_->TabStateChanged();
1403 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1404 // When the current tab's SSL state changes, we need to update the URL
1405 // bar to reflect the new state.
1406 DCHECK(source);
1407 if (tab_strip_model_->GetActiveWebContents() == source)
1408 UpdateToolbar(false);
1411 void Browser::AddNewContents(WebContents* source,
1412 WebContents* new_contents,
1413 WindowOpenDisposition disposition,
1414 const gfx::Rect& initial_rect,
1415 bool user_gesture,
1416 bool* was_blocked) {
1417 chrome::AddWebContents(this, source, new_contents, disposition, initial_rect,
1418 user_gesture, was_blocked);
1421 void Browser::ActivateContents(WebContents* contents) {
1422 tab_strip_model_->ActivateTabAt(
1423 tab_strip_model_->GetIndexOfWebContents(contents), false);
1424 window_->Activate();
1427 void Browser::DeactivateContents(WebContents* contents) {
1428 window_->Deactivate();
1431 void Browser::LoadingStateChanged(WebContents* source,
1432 bool to_different_document) {
1433 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1434 window_->UpdateTitleBar();
1436 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1437 if (source == selected_contents) {
1438 bool is_loading = source->IsLoading() && to_different_document;
1439 command_controller_->LoadingStateChanged(is_loading, false);
1440 if (GetStatusBubble()) {
1441 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1442 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1447 void Browser::CloseContents(WebContents* source) {
1448 bool can_close_contents;
1449 if (IsFastTabUnloadEnabled())
1450 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1451 else
1452 can_close_contents = unload_controller_->CanCloseContents(source);
1454 if (can_close_contents)
1455 chrome::CloseWebContents(this, source, true);
1458 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1459 if (!IsPopupOrPanel(source)) {
1460 NOTREACHED() << "moving invalid browser type";
1461 return;
1463 window_->SetBounds(pos);
1466 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1467 return is_type_popup();
1470 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1471 if (!GetStatusBubble())
1472 return;
1474 if (source == tab_strip_model_->GetActiveWebContents()) {
1475 PrefService* prefs = profile_->GetPrefs();
1476 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1480 void Browser::ContentsMouseEvent(
1481 WebContents* source, const gfx::Point& location, bool motion) {
1482 if (!GetStatusBubble())
1483 return;
1485 if (source == tab_strip_model_->GetActiveWebContents()) {
1486 GetStatusBubble()->MouseMoved(location, !motion);
1487 if (!motion)
1488 GetStatusBubble()->SetURL(GURL(), std::string());
1492 void Browser::ContentsZoomChange(bool zoom_in) {
1493 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1496 void Browser::WebContentsFocused(WebContents* contents) {
1497 window_->WebContentsFocused(contents);
1500 bool Browser::TakeFocus(content::WebContents* source,
1501 bool reverse) {
1502 content::NotificationService::current()->Notify(
1503 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1504 content::Source<Browser>(this),
1505 content::NotificationService::NoDetails());
1506 return false;
1509 gfx::Rect Browser::GetRootWindowResizerRect() const {
1510 return window_->GetRootWindowResizerRect();
1513 void Browser::BeforeUnloadFired(WebContents* web_contents,
1514 bool proceed,
1515 bool* proceed_to_fire_unload) {
1516 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1517 proceed, proceed_to_fire_unload))
1518 return;
1520 if (IsFastTabUnloadEnabled()) {
1521 *proceed_to_fire_unload =
1522 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1523 } else {
1524 *proceed_to_fire_unload =
1525 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1529 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1530 const content::NavigationEntry* entry =
1531 source->GetController().GetActiveEntry();
1532 if (entry) {
1533 GURL url = entry->GetURL();
1534 GURL virtual_url = entry->GetVirtualURL();
1535 if ((url.SchemeIs(content::kChromeUIScheme) &&
1536 url.host() == chrome::kChromeUINewTabHost) ||
1537 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1538 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1539 return true;
1543 return chrome::NavEntryIsInstantNTP(source, entry);
1546 void Browser::SetFocusToLocationBar(bool select_all) {
1547 // Two differences between this and FocusLocationBar():
1548 // (1) This doesn't get recorded in user metrics, since it's called
1549 // internally.
1550 // (2) This checks whether the location bar can be focused, and if not, clears
1551 // the focus. FocusLocationBar() is only reached when the location bar is
1552 // focusable, but this may be reached at other times, e.g. while in
1553 // fullscreen mode, where we need to leave focus in a consistent state.
1554 window_->SetFocusToLocationBar(select_all);
1557 int Browser::GetExtraRenderViewHeight() const {
1558 return window_->GetExtraRenderViewHeight();
1561 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1562 DCHECK(source);
1563 chrome::ViewSource(this, source);
1566 void Browser::ViewSourceForFrame(WebContents* source,
1567 const GURL& frame_url,
1568 const content::PageState& frame_page_state) {
1569 DCHECK(source);
1570 chrome::ViewSource(this, source, frame_url, frame_page_state);
1573 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1574 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1575 source);
1578 bool Browser::ShouldCreateWebContents(
1579 WebContents* web_contents,
1580 int route_id,
1581 int main_frame_route_id,
1582 WindowContainerType window_container_type,
1583 const base::string16& frame_name,
1584 const GURL& target_url,
1585 const std::string& partition_id,
1586 content::SessionStorageNamespace* session_storage_namespace) {
1587 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1588 // If a BackgroundContents is created, suppress the normal WebContents.
1589 return !MaybeCreateBackgroundContents(route_id,
1590 main_frame_route_id,
1591 web_contents,
1592 frame_name,
1593 target_url,
1594 partition_id,
1595 session_storage_namespace);
1598 return true;
1601 void Browser::WebContentsCreated(WebContents* source_contents,
1602 int opener_render_frame_id,
1603 const base::string16& frame_name,
1604 const GURL& target_url,
1605 WebContents* new_contents) {
1606 // Adopt the WebContents now, so all observers are in place, as the network
1607 // requests for its initial navigation will start immediately. The WebContents
1608 // will later be inserted into this browser using Browser::Navigate via
1609 // AddNewContents.
1610 TabHelpers::AttachTabHelpers(new_contents);
1612 // Notify.
1613 RetargetingDetails details;
1614 details.source_web_contents = source_contents;
1615 details.source_render_frame_id = opener_render_frame_id;
1616 details.target_url = target_url;
1617 details.target_web_contents = new_contents;
1618 details.not_yet_in_tabstrip = true;
1619 content::NotificationService::current()->Notify(
1620 chrome::NOTIFICATION_RETARGETING,
1621 content::Source<Profile>(profile_),
1622 content::Details<RetargetingDetails>(&details));
1625 void Browser::RendererUnresponsive(WebContents* source) {
1626 // Ignore hangs if a tab is blocked.
1627 int index = tab_strip_model_->GetIndexOfWebContents(source);
1628 DCHECK_NE(TabStripModel::kNoTab, index);
1629 if (tab_strip_model_->IsTabBlocked(index))
1630 return;
1632 TabDialogs::FromWebContents(source)->ShowHungRendererDialog();
1635 void Browser::RendererResponsive(WebContents* source) {
1636 TabDialogs::FromWebContents(source)->HideHungRendererDialog();
1639 void Browser::WorkerCrashed(WebContents* source) {
1640 SimpleAlertInfoBarDelegate::Create(
1641 InfoBarService::FromWebContents(source),
1642 infobars::InfoBarDelegate::kNoIconID,
1643 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1646 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1647 if (web_contents == tab_strip_model_->GetActiveWebContents())
1648 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1651 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1652 WebContents* source) {
1653 return app_modal::JavaScriptDialogManager::GetInstance();
1656 content::ColorChooser* Browser::OpenColorChooser(
1657 WebContents* web_contents,
1658 SkColor initial_color,
1659 const std::vector<content::ColorSuggestion>& suggestions) {
1660 return chrome::ShowColorChooser(web_contents, initial_color);
1663 void Browser::RunFileChooser(WebContents* web_contents,
1664 const content::FileChooserParams& params) {
1665 FileSelectHelper::RunFileChooser(web_contents, params);
1668 void Browser::EnumerateDirectory(WebContents* web_contents,
1669 int request_id,
1670 const base::FilePath& path) {
1671 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1674 bool Browser::EmbedsFullscreenWidget() const {
1675 return true;
1678 void Browser::EnterFullscreenModeForTab(WebContents* web_contents,
1679 const GURL& origin) {
1680 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1681 web_contents, origin);
1684 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1685 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1686 web_contents);
1689 bool Browser::IsFullscreenForTabOrPending(
1690 const WebContents* web_contents) const {
1691 return exclusive_access_manager_->fullscreen_controller()
1692 ->IsFullscreenForTabOrPending(web_contents);
1695 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1696 const std::string& protocol,
1697 const GURL& url,
1698 bool user_gesture) {
1699 content::BrowserContext* context = web_contents->GetBrowserContext();
1700 if (context->IsOffTheRecord())
1701 return;
1703 ProtocolHandler handler =
1704 ProtocolHandler::CreateProtocolHandler(protocol, url);
1706 ProtocolHandlerRegistry* registry =
1707 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1708 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1709 return;
1711 TabSpecificContentSettings* tab_content_settings =
1712 TabSpecificContentSettings::FromWebContents(web_contents);
1713 if (!user_gesture && window_) {
1714 tab_content_settings->set_pending_protocol_handler(handler);
1715 tab_content_settings->set_previous_protocol_handler(
1716 registry->GetHandlerFor(handler.protocol()));
1717 window_->GetLocationBar()->UpdateContentSettingsIcons();
1718 return;
1721 // Make sure content-setting icon is turned off in case the page does
1722 // ungestured and gestured RPH calls.
1723 if (window_) {
1724 tab_content_settings->ClearPendingProtocolHandler();
1725 window_->GetLocationBar()->UpdateContentSettingsIcons();
1728 PermissionBubbleManager* bubble_manager =
1729 PermissionBubbleManager::FromWebContents(web_contents);
1730 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1731 bubble_manager->AddRequest(
1732 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1733 url, user_gesture));
1734 } else {
1735 RegisterProtocolHandlerInfoBarDelegate::Create(
1736 InfoBarService::FromWebContents(web_contents), registry, handler);
1740 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1741 const std::string& protocol,
1742 const GURL& url,
1743 bool user_gesture) {
1744 // user_gesture will be used in case we decide to have confirmation bubble
1745 // for user while un-registering the handler.
1746 content::BrowserContext* context = web_contents->GetBrowserContext();
1747 if (context->IsOffTheRecord())
1748 return;
1750 ProtocolHandler handler =
1751 ProtocolHandler::CreateProtocolHandler(protocol, url);
1753 ProtocolHandlerRegistry* registry =
1754 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1755 registry->RemoveHandler(handler);
1758 void Browser::UpdatePreferredSize(WebContents* source,
1759 const gfx::Size& pref_size) {
1760 window_->UpdatePreferredSize(source, pref_size);
1763 void Browser::ResizeDueToAutoResize(WebContents* source,
1764 const gfx::Size& new_size) {
1765 window_->ResizeDueToAutoResize(source, new_size);
1768 void Browser::FindReply(WebContents* web_contents,
1769 int request_id,
1770 int number_of_matches,
1771 const gfx::Rect& selection_rect,
1772 int active_match_ordinal,
1773 bool final_update) {
1774 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1775 if (!find_tab_helper)
1776 return;
1778 find_tab_helper->HandleFindReply(request_id,
1779 number_of_matches,
1780 selection_rect,
1781 active_match_ordinal,
1782 final_update);
1785 void Browser::RequestToLockMouse(WebContents* web_contents,
1786 bool user_gesture,
1787 bool last_unlocked_by_target) {
1788 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
1789 web_contents, user_gesture, last_unlocked_by_target);
1792 void Browser::LostMouseLock() {
1793 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
1796 void Browser::RequestMediaAccessPermission(
1797 content::WebContents* web_contents,
1798 const content::MediaStreamRequest& request,
1799 const content::MediaResponseCallback& callback) {
1800 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1803 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1804 const GURL& security_origin,
1805 content::MediaStreamType type) {
1806 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1809 bool Browser::RequestPpapiBrokerPermission(
1810 WebContents* web_contents,
1811 const GURL& url,
1812 const base::FilePath& plugin_path,
1813 const base::Callback<void(bool)>& callback) {
1814 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1815 return true;
1818 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1819 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1820 // would disappear on non-NTP pages, resulting in a bigger size for the new
1821 // render view.
1822 gfx::Size size = web_contents->GetContainerBounds().size();
1823 // Don't change render view size if bookmark bar is currently not detached,
1824 // or there's no pending entry, or navigating to a NTP page.
1825 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1826 return size;
1827 const NavigationEntry* pending_entry =
1828 web_contents->GetController().GetPendingEntry();
1829 if (pending_entry &&
1830 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1831 size.Enlarge(
1832 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1834 return size;
1837 ///////////////////////////////////////////////////////////////////////////////
1838 // Browser, CoreTabHelperDelegate implementation:
1840 void Browser::SwapTabContents(content::WebContents* old_contents,
1841 content::WebContents* new_contents,
1842 bool did_start_load,
1843 bool did_finish_load) {
1844 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1845 DCHECK_NE(TabStripModel::kNoTab, index);
1846 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1849 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1850 return chrome::CanReload(this);
1853 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1854 return chrome::CanSavePage(this);
1857 ///////////////////////////////////////////////////////////////////////////////
1858 // Browser, SearchEngineTabHelperDelegate implementation:
1860 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1861 Profile* profile) {
1862 window()->ConfirmAddSearchProvider(template_url, profile);
1865 ///////////////////////////////////////////////////////////////////////////////
1866 // Browser, SearchTabHelperDelegate implementation:
1868 void Browser::NavigateOnThumbnailClick(const GURL& url,
1869 WindowOpenDisposition disposition,
1870 content::WebContents* source_contents) {
1871 DCHECK(source_contents);
1872 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1873 // gets called to handle clicks in the new tab page (to navigate to most
1874 // visited item URLs) and in the search results page (to navigate to
1875 // privileged destinations (e.g. chrome://URLs)).
1877 // TODO(kmadhusu): Page transitions to privileged destinations should be
1878 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1879 chrome::NavigateParams params(this, url,
1880 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1881 params.referrer = content::Referrer();
1882 params.source_contents = source_contents;
1883 params.disposition = disposition;
1884 params.is_renderer_initiated = false;
1885 params.initiating_profile = profile_;
1886 chrome::Navigate(&params);
1889 void Browser::OnWebContentsInstantSupportDisabled(
1890 const content::WebContents* web_contents) {
1891 DCHECK(web_contents);
1892 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1893 UpdateToolbar(false);
1896 OmniboxView* Browser::GetOmniboxView() {
1897 return window_->GetLocationBar()->GetOmniboxView();
1900 std::set<std::string> Browser::GetOpenUrls() {
1901 scoped_refptr<history::TopSites> top_sites =
1902 TopSitesFactory::GetForProfile(profile_);
1903 if (!top_sites) // NULL for Incognito profiles.
1904 return std::set<std::string>();
1906 std::set<std::string> open_urls;
1907 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1908 return open_urls;
1911 ///////////////////////////////////////////////////////////////////////////////
1912 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1914 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1915 bool blocked) {
1916 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1917 if (index == TabStripModel::kNoTab) {
1918 NOTREACHED();
1919 return;
1921 tab_strip_model_->SetTabBlocked(index, blocked);
1922 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1923 web_contents->Focus();
1926 web_modal::WebContentsModalDialogHost*
1927 Browser::GetWebContentsModalDialogHost() {
1928 return window_->GetWebContentsModalDialogHost();
1931 ///////////////////////////////////////////////////////////////////////////////
1932 // Browser, BookmarkTabHelperDelegate implementation:
1934 void Browser::URLStarredChanged(content::WebContents* web_contents,
1935 bool starred) {
1936 if (web_contents == tab_strip_model_->GetActiveWebContents())
1937 window_->SetStarredState(starred);
1940 ///////////////////////////////////////////////////////////////////////////////
1941 // Browser, ZoomObserver implementation:
1943 void Browser::OnZoomChanged(
1944 const ui_zoom::ZoomController::ZoomChangedEventData& data) {
1945 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1946 window_->ZoomChangedForActiveTab(data.can_show_bubble);
1947 // Change the zoom commands state based on the zoom state
1948 command_controller_->ZoomStateChanged();
1952 ///////////////////////////////////////////////////////////////////////////////
1953 // Browser, ui::SelectFileDialog::Listener implementation:
1955 void Browser::FileSelected(const base::FilePath& path, int index,
1956 void* params) {
1957 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1960 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1961 int index,
1962 void* params) {
1963 profile_->set_last_selected_directory(file_info.file_path.DirName());
1965 GURL url = net::FilePathToFileURL(file_info.local_path);
1967 #if defined(OS_CHROMEOS)
1968 const GURL external_url =
1969 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
1970 if (!external_url.is_empty())
1971 url = external_url;
1972 #endif
1974 if (url.is_empty())
1975 return;
1977 OpenURL(OpenURLParams(
1978 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
1981 ///////////////////////////////////////////////////////////////////////////////
1982 // Browser, content::NotificationObserver implementation:
1984 void Browser::Observe(int type,
1985 const content::NotificationSource& source,
1986 const content::NotificationDetails& details) {
1987 switch (type) {
1988 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1989 Profile* profile = content::Source<Profile>(source).ptr();
1990 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1991 window()->GetLocationBar()->UpdatePageActions();
1992 break;
1995 #if defined(ENABLE_THEMES)
1996 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1997 window()->UserChangedTheme();
1998 break;
1999 #endif
2001 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2002 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2003 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2004 LocationBar* location_bar = window()->GetLocationBar();
2005 if (location_bar)
2006 location_bar->UpdateContentSettingsIcons();
2008 break;
2011 default:
2012 NOTREACHED() << "Got a notification we didn't register for.";
2016 #if defined(ENABLE_EXTENSIONS)
2017 ///////////////////////////////////////////////////////////////////////////////
2018 // Browser, extensions::ExtensionRegistryObserver implementation:
2020 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
2021 const extensions::Extension* extension,
2022 extensions::UninstallReason reason) {
2023 // During window creation on Windows we may end up calling into
2024 // SHAppBarMessage, which internally spawns a nested message loop.This
2025 // makes it possible for us to end up here before window creation has
2026 // completed, at which point window_ is NULL. See 94752 for details.
2028 if (window() && window()->GetLocationBar())
2029 window()->GetLocationBar()->UpdatePageActions();
2032 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2033 const extensions::Extension* extension) {
2034 command_controller_->ExtensionStateChanged();
2037 void Browser::OnExtensionUnloaded(
2038 content::BrowserContext* browser_context,
2039 const extensions::Extension* extension,
2040 extensions::UnloadedExtensionInfo::Reason reason) {
2041 command_controller_->ExtensionStateChanged();
2042 if (window()->GetLocationBar())
2043 window()->GetLocationBar()->UpdatePageActions();
2045 // Close any tabs from the unloaded extension, unless it's terminated,
2046 // in which case let the sad tabs remain.
2047 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2048 // Iterate backwards as we may remove items while iterating.
2049 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2050 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2051 // Two cases are handled here:
2053 // - The scheme check is for when an extension page is loaded in a
2054 // tab, e.g. chrome-extension://id/page.html.
2055 // - The extension_app check is for apps, which can have non-extension
2056 // schemes, e.g. https://mail.google.com if you have the Gmail app
2057 // installed.
2058 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2059 web_contents->GetURL().host() == extension->id()) ||
2060 (extensions::TabHelper::FromWebContents(web_contents)
2061 ->extension_app() == extension)) {
2062 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2067 #endif // defined(ENABLE_EXTENSIONS)
2069 ///////////////////////////////////////////////////////////////////////////////
2070 // Browser, translate::ContentTranslateDriver::Observer implementation:
2072 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2073 DCHECK(source);
2074 if (tab_strip_model_->GetActiveWebContents() == source) {
2075 window_->SetTranslateIconToggled(
2076 ChromeTranslateClient::FromWebContents(
2077 source)->GetLanguageState().IsPageTranslated());
2081 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2082 DCHECK(source);
2083 if (tab_strip_model_->GetActiveWebContents() == source)
2084 UpdateToolbar(false);
2087 ///////////////////////////////////////////////////////////////////////////////
2088 // Browser, Command and state updating (private):
2090 void Browser::OnDevToolsDisabledChanged() {
2091 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2092 content::DevToolsAgentHost::DetachAllClients();
2095 ///////////////////////////////////////////////////////////////////////////////
2096 // Browser, UI update coalescing and handling (private):
2098 void Browser::UpdateToolbar(bool should_restore_state) {
2099 window_->UpdateToolbar(should_restore_state ?
2100 tab_strip_model_->GetActiveWebContents() : NULL);
2103 void Browser::ScheduleUIUpdate(WebContents* source,
2104 unsigned changed_flags) {
2105 DCHECK(source);
2106 int index = tab_strip_model_->GetIndexOfWebContents(source);
2107 DCHECK_NE(TabStripModel::kNoTab, index);
2109 // Do some synchronous updates.
2110 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2111 if (source == tab_strip_model_->GetActiveWebContents()) {
2112 // Only update the URL for the current tab. Note that we do not update
2113 // the navigation commands since those would have already been updated
2114 // synchronously by NavigationStateChanged.
2115 UpdateToolbar(false);
2116 } else {
2117 // Clear the saved tab state for the tab that navigated, so that we don't
2118 // restore any user text after the old URL has been invalidated (e.g.,
2119 // after a new navigation commits in that tab while unfocused).
2120 window_->ResetToolbarTabState(source);
2122 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2124 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2125 // Update the loading state synchronously. This is so the throbber will
2126 // immediately start/stop, which gives a more snappy feel. We want to do
2127 // this for any tab so they start & stop quickly.
2128 tab_strip_model_->UpdateWebContentsStateAt(
2129 tab_strip_model_->GetIndexOfWebContents(source),
2130 TabStripModelObserver::LOADING_ONLY);
2131 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2132 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2133 // changed_flags.
2136 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2137 // To correctly calculate whether the title changed while not loading
2138 // we need to process the update synchronously. This state only matters for
2139 // the TabStripModel, so we notify the TabStripModel now and notify others
2140 // asynchronously.
2141 tab_strip_model_->UpdateWebContentsStateAt(
2142 tab_strip_model_->GetIndexOfWebContents(source),
2143 TabStripModelObserver::TITLE_NOT_LOADING);
2146 // If the only updates were synchronously handled above, we're done.
2147 if (changed_flags == 0)
2148 return;
2150 // Save the dirty bits.
2151 scheduled_updates_[source] |= changed_flags;
2153 if (!chrome_updater_factory_.HasWeakPtrs()) {
2154 // No task currently scheduled, start another.
2155 base::MessageLoop::current()->PostDelayedTask(
2156 FROM_HERE,
2157 base::Bind(&Browser::ProcessPendingUIUpdates,
2158 chrome_updater_factory_.GetWeakPtr()),
2159 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2163 void Browser::ProcessPendingUIUpdates() {
2164 #ifndef NDEBUG
2165 // Validate that all tabs we have pending updates for exist. This is scary
2166 // because the pending list must be kept in sync with any detached or
2167 // deleted tabs.
2168 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2169 i != scheduled_updates_.end(); ++i) {
2170 bool found = false;
2171 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2172 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2173 found = true;
2174 break;
2177 DCHECK(found);
2179 #endif
2181 chrome_updater_factory_.InvalidateWeakPtrs();
2183 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2184 i != scheduled_updates_.end(); ++i) {
2185 // Do not dereference |contents|, it may be out-of-date!
2186 const WebContents* contents = i->first;
2187 unsigned flags = i->second;
2189 if (contents == tab_strip_model_->GetActiveWebContents()) {
2190 // Updates that only matter when the tab is selected go here.
2192 // Updating the URL happens synchronously in ScheduleUIUpdate.
2193 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2194 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2195 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2198 if (flags & (content::INVALIDATE_TYPE_TAB |
2199 content::INVALIDATE_TYPE_TITLE)) {
2200 window_->UpdateTitleBar();
2204 // Updates that don't depend upon the selected state go here.
2205 if (flags &
2206 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2207 tab_strip_model_->UpdateWebContentsStateAt(
2208 tab_strip_model_->GetIndexOfWebContents(contents),
2209 TabStripModelObserver::ALL);
2212 // Update the bookmark bar. It may happen that the tab is crashed, and if
2213 // so, the bookmark bar should be hidden.
2214 if (flags & content::INVALIDATE_TYPE_TAB)
2215 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2217 // We don't need to process INVALIDATE_STATE, since that's not visible.
2220 scheduled_updates_.clear();
2223 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2224 if (!contents)
2225 return;
2227 UpdateMap::iterator i = scheduled_updates_.find(contents);
2228 if (i != scheduled_updates_.end())
2229 scheduled_updates_.erase(i);
2232 ///////////////////////////////////////////////////////////////////////////////
2233 // Browser, Getters for UI (private):
2235 StatusBubble* Browser::GetStatusBubble() {
2236 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2237 if (chrome::IsRunningInAppMode())
2238 return NULL;
2240 return window_ ? window_->GetStatusBubble() : NULL;
2243 ///////////////////////////////////////////////////////////////////////////////
2244 // Browser, Session restore functions (private):
2246 void Browser::SyncHistoryWithTabs(int index) {
2247 SessionService* session_service =
2248 SessionServiceFactory::GetForProfileIfExisting(profile());
2249 if (session_service) {
2250 for (int i = index; i < tab_strip_model_->count(); ++i) {
2251 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2252 if (web_contents) {
2253 SessionTabHelper* session_tab_helper =
2254 SessionTabHelper::FromWebContents(web_contents);
2255 session_service->SetTabIndexInWindow(
2256 session_id(), session_tab_helper->session_id(), i);
2257 session_service->SetPinnedState(
2258 session_id(),
2259 session_tab_helper->session_id(),
2260 tab_strip_model_->IsTabPinned(i));
2266 ///////////////////////////////////////////////////////////////////////////////
2267 // Browser, In-progress download termination handling (private):
2269 bool Browser::CanCloseWithInProgressDownloads() {
2270 // If we've prompted, we need to hear from the user before we
2271 // can close.
2272 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2273 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2275 int num_downloads_blocking;
2276 Browser::DownloadClosePreventionType dialog_type =
2277 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2278 if (dialog_type == DOWNLOAD_CLOSE_OK)
2279 return true;
2281 // Closing this window will kill some downloads; prompt to make sure
2282 // that's ok.
2283 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2284 window_->ConfirmBrowserCloseWithPendingDownloads(
2285 num_downloads_blocking,
2286 dialog_type,
2287 false,
2288 base::Bind(&Browser::InProgressDownloadResponse,
2289 weak_factory_.GetWeakPtr()));
2291 // Return false so the browser does not close. We'll close if the user
2292 // confirms in the dialog.
2293 return false;
2296 ///////////////////////////////////////////////////////////////////////////////
2297 // Browser, Assorted utility functions (private):
2299 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2300 Browser* delegate = set_delegate ? this : NULL;
2301 // WebContents...
2302 web_contents->SetDelegate(delegate);
2304 // ...and all the helpers.
2305 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2306 WebContentsModalDialogManager::FromWebContents(web_contents)->
2307 SetDelegate(delegate);
2308 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2309 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2310 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2311 translate::ContentTranslateDriver& content_translate_driver =
2312 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2313 if (delegate) {
2314 ui_zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2315 content_translate_driver.AddObserver(this);
2316 } else {
2317 ui_zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(
2318 this);
2319 content_translate_driver.RemoveObserver(this);
2323 void Browser::CloseFrame() {
2324 window_->Close();
2327 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2328 int index,
2329 DetachType type) {
2330 if (type == DETACH_TYPE_DETACH) {
2331 // Save the current location bar state, but only if the tab being detached
2332 // is the selected tab. Because saving state can conditionally revert the
2333 // location bar, saving the current tab's location bar state to a
2334 // non-selected tab can corrupt both tabs.
2335 if (contents == tab_strip_model_->GetActiveWebContents()) {
2336 LocationBar* location_bar = window()->GetLocationBar();
2337 if (location_bar)
2338 location_bar->SaveStateToContents(contents);
2341 if (!tab_strip_model_->closing_all())
2342 SyncHistoryWithTabs(0);
2345 SetAsDelegate(contents, false);
2346 RemoveScheduledUpdatesFor(contents);
2348 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2349 find_bar_controller_->ChangeWebContents(NULL);
2352 // Stop observing search model changes for this tab.
2353 search_delegate_->OnTabDetached(contents);
2355 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2356 if (interstitial_observers_[i]->web_contents() != contents)
2357 continue;
2359 delete interstitial_observers_[i];
2360 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2361 return;
2365 bool Browser::ShouldShowLocationBar() const {
2366 // Tabbed browser always show a location bar.
2367 if (is_type_tabbed())
2368 return true;
2370 // Trusted app windows and system windows never show a location bar.
2371 return !is_app() && !is_trusted_source();
2374 bool Browser::ShouldUseWebAppFrame() const {
2375 // Only use the web app frame for apps in ash, and only if bookmark apps are
2376 // enabled.
2377 if (!is_app() || host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH ||
2378 !IsWebAppFrameEnabled()) {
2379 return false;
2382 // Use the web app frame for hosted apps (which include bookmark apps).
2383 const std::string extension_id =
2384 web_app::GetExtensionIdFromApplicationName(app_name());
2385 const extensions::Extension* extension =
2386 extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
2387 extension_id, extensions::ExtensionRegistry::EVERYTHING);
2388 return extension && extension->is_hosted_app();
2391 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2392 bool check_fullscreen) const {
2393 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2395 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2397 if (is_type_tabbed())
2398 features |= FEATURE_BOOKMARKBAR;
2400 if (!hide_ui_for_fullscreen) {
2401 if (!is_type_tabbed())
2402 features |= FEATURE_TITLEBAR;
2404 if (is_type_tabbed())
2405 features |= FEATURE_TABSTRIP;
2407 if (is_type_tabbed())
2408 features |= FEATURE_TOOLBAR;
2410 if (ShouldShowLocationBar())
2411 features |= FEATURE_LOCATIONBAR;
2413 if (ShouldUseWebAppFrame())
2414 features |= FEATURE_WEBAPPFRAME;
2416 return !!(features & feature);
2419 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2420 BookmarkBar::State state;
2421 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2422 // mode, unless on the new tab page.
2423 if (profile_->IsGuestSession()) {
2424 state = BookmarkBar::HIDDEN;
2425 } else if (browser_defaults::bookmarks_enabled &&
2426 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2427 !ShouldHideUIForFullscreen()) {
2428 state = BookmarkBar::SHOW;
2429 } else {
2430 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2431 BookmarkTabHelper* bookmark_tab_helper =
2432 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2433 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2434 state = BookmarkBar::DETACHED;
2435 else
2436 state = BookmarkBar::HIDDEN;
2439 if (state == bookmark_bar_state_)
2440 return;
2442 bookmark_bar_state_ = state;
2444 if (!window_)
2445 return; // This is called from the constructor when window_ is NULL.
2447 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2448 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2449 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2450 // end up querying state once they process the tab switch.
2451 return;
2454 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2455 window_->BookmarkBarStateChanged(should_animate ?
2456 BookmarkBar::ANIMATE_STATE_CHANGE :
2457 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2460 bool Browser::ShouldHideUIForFullscreen() const {
2461 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2462 // keep the controls in a slide-down panel.
2463 return window_ && window_->ShouldHideUIForFullscreen();
2466 bool Browser::MaybeCreateBackgroundContents(
2467 int route_id,
2468 int main_frame_route_id,
2469 WebContents* opener_web_contents,
2470 const base::string16& frame_name,
2471 const GURL& target_url,
2472 const std::string& partition_id,
2473 content::SessionStorageNamespace* session_storage_namespace) {
2474 GURL opener_url = opener_web_contents->GetURL();
2475 ExtensionService* extensions_service =
2476 extensions::ExtensionSystem::Get(profile_)->extension_service();
2478 if (!opener_url.is_valid() ||
2479 frame_name.empty() ||
2480 !extensions_service ||
2481 !extensions_service->is_ready())
2482 return false;
2484 // Only hosted apps have web extents, so this ensures that only hosted apps
2485 // can create BackgroundContents. We don't have to check for background
2486 // permission as that is checked in RenderMessageFilter when the CreateWindow
2487 // message is processed.
2488 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
2489 ->enabled_extensions()
2490 .GetHostedAppByURL(opener_url);
2491 if (!extension)
2492 return false;
2494 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2495 BackgroundContentsService* service =
2496 BackgroundContentsServiceFactory::GetForProfile(profile_);
2497 if (!service)
2498 return false;
2500 // Ensure that we're trying to open this from the extension's process.
2501 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2502 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2503 if (!opener_site_instance->GetProcess() ||
2504 !process_map->Contains(
2505 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2506 return false;
2509 // Only allow a single background contents per app.
2510 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2511 BackgroundContents* existing =
2512 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2513 if (existing) {
2514 // For non-scriptable background contents, ignore the request altogether,
2515 // (returning true, so that a regular WebContents isn't created either).
2516 if (!allow_js_access)
2517 return true;
2518 // For scriptable background pages, if one already exists, close it (even
2519 // if it was specified in the manifest).
2520 delete existing;
2523 // If script access is not allowed, create the the background contents in a
2524 // new SiteInstance, so that a separate process is used.
2525 scoped_refptr<content::SiteInstance> site_instance =
2526 allow_js_access ?
2527 opener_site_instance :
2528 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2530 // Passed all the checks, so this should be created as a BackgroundContents.
2531 BackgroundContents* contents =
2532 service->CreateBackgroundContents(site_instance.get(),
2533 route_id,
2534 main_frame_route_id,
2535 profile_,
2536 frame_name,
2537 base::ASCIIToUTF16(extension->id()),
2538 partition_id,
2539 session_storage_namespace);
2541 // When a separate process is used, the original renderer cannot access the
2542 // new window later, thus we need to navigate the window now.
2543 if (contents && !allow_js_access) {
2544 contents->web_contents()->GetController().LoadURL(
2545 target_url,
2546 content::Referrer(),
2547 ui::PAGE_TRANSITION_LINK,
2548 std::string()); // No extra headers.
2551 return contents != NULL;