1// Copyright (c) 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.
4
5#include "chrome/browser/tab_contents/background_contents.h"
6
7#include "chrome/browser/background/background_contents_service.h"
8#include "chrome/browser/chrome_notification_types.h"
9#include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
10#include "chrome/browser/profiles/profile.h"
11#include "chrome/browser/renderer_preferences_util.h"
12#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
13#include "chrome/common/url_constants.h"
14#include "content/public/browser/notification_service.h"
15#include "content/public/browser/render_view_host.h"
16#include "content/public/browser/session_storage_namespace.h"
17#include "content/public/browser/site_instance.h"
18#include "content/public/browser/web_contents.h"
19#include "extensions/browser/view_type_utils.h"
20#include "ui/gfx/rect.h"
21
22using content::SiteInstance;
23using content::WebContents;
24
25BackgroundContents::BackgroundContents(
26    SiteInstance* site_instance,
27    int routing_id,
28    Delegate* delegate,
29    const std::string& partition_id,
30    content::SessionStorageNamespace* session_storage_namespace)
31    : delegate_(delegate) {
32  profile_ = Profile::FromBrowserContext(
33      site_instance->GetBrowserContext());
34
35  WebContents::CreateParams create_params(profile_, site_instance);
36  create_params.routing_id = routing_id;
37  if (session_storage_namespace) {
38    content::SessionStorageNamespaceMap session_storage_namespace_map;
39    session_storage_namespace_map.insert(
40        std::make_pair(partition_id, session_storage_namespace));
41    web_contents_.reset(WebContents::CreateWithSessionStorage(
42        create_params, session_storage_namespace_map));
43  } else {
44    web_contents_.reset(WebContents::Create(create_params));
45  }
46  extensions::SetViewType(
47      web_contents_.get(), extensions::VIEW_TYPE_BACKGROUND_CONTENTS);
48  web_contents_->SetDelegate(this);
49  content::WebContentsObserver::Observe(web_contents_.get());
50  extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
51      web_contents_.get());
52
53  // Close ourselves when the application is shutting down.
54  registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
55                 content::NotificationService::AllSources());
56
57  // Register for our parent profile to shutdown, so we can shut ourselves down
58  // as well (should only be called for OTR profiles, as we should receive
59  // APP_TERMINATING before non-OTR profiles are destroyed).
60  registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
61                 content::Source<Profile>(profile_));
62}
63
64// Exposed to allow creating mocks.
65BackgroundContents::BackgroundContents()
66    : delegate_(NULL),
67      profile_(NULL) {
68}
69
70BackgroundContents::~BackgroundContents() {
71  if (!web_contents_.get())   // Will be null for unit tests.
72    return;
73
74  // Unregister for any notifications before notifying observers that we are
75  // going away - this prevents any re-entrancy due to chained notifications
76  // (http://crbug.com/237781).
77  registrar_.RemoveAll();
78
79  content::NotificationService::current()->Notify(
80      chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED,
81      content::Source<Profile>(profile_),
82      content::Details<BackgroundContents>(this));
83}
84
85const GURL& BackgroundContents::GetURL() const {
86  return web_contents_.get() ? web_contents_->GetURL() : GURL::EmptyGURL();
87}
88
89void BackgroundContents::CloseContents(WebContents* source) {
90  content::NotificationService::current()->Notify(
91      chrome::NOTIFICATION_BACKGROUND_CONTENTS_CLOSED,
92      content::Source<Profile>(profile_),
93      content::Details<BackgroundContents>(this));
94  delete this;
95}
96
97bool BackgroundContents::ShouldSuppressDialogs() {
98  return true;
99}
100
101void BackgroundContents::DidNavigateMainFramePostCommit(WebContents* tab) {
102  // Note: because BackgroundContents are only available to extension apps,
103  // navigation is limited to urls within the app's extent. This is enforced in
104  // RenderView::decidePolicyForNavigation. If BackgroundContents become
105  // available as a part of the web platform, it probably makes sense to have
106  // some way to scope navigation of a background page to its opener's security
107  // origin. Note: if the first navigation is to a URL outside the app's
108  // extent a background page will be opened but will remain at about:blank.
109  content::NotificationService::current()->Notify(
110      chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED,
111      content::Source<Profile>(profile_),
112      content::Details<BackgroundContents>(this));
113}
114
115// Forward requests to add a new WebContents to our delegate.
116void BackgroundContents::AddNewContents(WebContents* source,
117                                        WebContents* new_contents,
118                                        WindowOpenDisposition disposition,
119                                        const gfx::Rect& initial_pos,
120                                        bool user_gesture,
121                                        bool* was_blocked) {
122  delegate_->AddWebContents(
123      new_contents, disposition, initial_pos, user_gesture, was_blocked);
124}
125
126bool BackgroundContents::IsNeverVisible(content::WebContents* web_contents) {
127  DCHECK_EQ(extensions::VIEW_TYPE_BACKGROUND_CONTENTS,
128            extensions::GetViewType(web_contents));
129  return true;
130}
131
132void BackgroundContents::RenderProcessGone(base::TerminationStatus status) {
133  content::NotificationService::current()->Notify(
134      chrome::NOTIFICATION_BACKGROUND_CONTENTS_TERMINATED,
135      content::Source<Profile>(profile_),
136      content::Details<BackgroundContents>(this));
137
138  // Our RenderView went away, so we should go away also, so killing the process
139  // via the TaskManager doesn't permanently leave a BackgroundContents hanging
140  // around the system, blocking future instances from being created
141  // <http://crbug.com/65189>.
142  delete this;
143}
144
145void BackgroundContents::Observe(int type,
146                                 const content::NotificationSource& source,
147                                 const content::NotificationDetails& details) {
148  // TODO(rafaelw): Implement pagegroup ref-counting so that non-persistent
149  // background pages are closed when the last referencing frame is closed.
150  switch (type) {
151    case chrome::NOTIFICATION_PROFILE_DESTROYED:
152    case chrome::NOTIFICATION_APP_TERMINATING: {
153      delete this;
154      break;
155    }
156    default:
157      NOTREACHED() << "Unexpected notification sent.";
158      break;
159  }
160}
161