[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / extensions / browser / process_manager.h
blob658fcd38612f3398922a5f258ce12dc1a0a67a3e
1 // Copyright 2013 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 #ifndef EXTENSIONS_BROWSER_PROCESS_MANAGER_H_
6 #define EXTENSIONS_BROWSER_PROCESS_MANAGER_H_
8 #include <map>
9 #include <set>
10 #include <string>
12 #include "base/callback.h"
13 #include "base/compiler_specific.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/time/time.h"
18 #include "components/keyed_service/core/keyed_service.h"
19 #include "content/public/browser/notification_observer.h"
20 #include "content/public/browser/notification_registrar.h"
21 #include "extensions/common/view_type.h"
23 class GURL;
25 namespace content {
26 class BrowserContext;
27 class DevToolsAgentHost;
28 class RenderViewHost;
29 class RenderFrameHost;
30 class SiteInstance;
33 namespace extensions {
35 class Extension;
36 class ExtensionHost;
37 class ExtensionRegistry;
38 class ProcessManagerDelegate;
39 class ProcessManagerObserver;
41 // Manages dynamic state of running Chromium extensions. There is one instance
42 // of this class per Profile. OTR Profiles have a separate instance that keeps
43 // track of split-mode extensions only.
44 class ProcessManager : public KeyedService,
45 public content::NotificationObserver {
46 public:
47 typedef std::set<extensions::ExtensionHost*> ExtensionHostSet;
48 typedef ExtensionHostSet::const_iterator const_iterator;
50 static ProcessManager* Get(content::BrowserContext* context);
51 ~ProcessManager() override;
53 const ExtensionHostSet& background_hosts() const {
54 return background_hosts_;
57 typedef std::set<content::RenderViewHost*> ViewSet;
58 const ViewSet GetAllViews() const;
60 // The typical observer interface.
61 void AddObserver(ProcessManagerObserver* observer);
62 void RemoveObserver(ProcessManagerObserver* observer);
64 // Creates a new UI-less extension instance. Like CreateViewHost, but not
65 // displayed anywhere. Returns false if no background host can be created,
66 // for example for hosted apps and extensions that aren't enabled in
67 // Incognito.
68 virtual bool CreateBackgroundHost(const Extension* extension,
69 const GURL& url);
71 // Gets the ExtensionHost for the background page for an extension, or NULL if
72 // the extension isn't running or doesn't have a background page.
73 ExtensionHost* GetBackgroundHostForExtension(const std::string& extension_id);
75 // Returns the SiteInstance that the given URL belongs to.
76 // TODO(aa): This only returns correct results for extensions and packaged
77 // apps, not hosted apps.
78 virtual content::SiteInstance* GetSiteInstanceForURL(const GURL& url);
80 // If the view isn't keeping the lazy background page alive, increments the
81 // keepalive count to do so.
82 void AcquireLazyKeepaliveCountForView(
83 content::RenderViewHost* render_view_host);
85 // If the view is keeping the lazy background page alive, decrements the
86 // keepalive count to stop doing it.
87 void ReleaseLazyKeepaliveCountForView(
88 content::RenderViewHost* render_view_host);
90 // Unregisters a RenderViewHost as hosting any extension.
91 void UnregisterRenderViewHost(content::RenderViewHost* render_view_host);
93 // Returns all RenderViewHosts that are registered for the specified
94 // extension.
95 std::set<content::RenderViewHost*> GetRenderViewHostsForExtension(
96 const std::string& extension_id);
98 // Returns the extension associated with the specified RenderViewHost, or
99 // NULL.
100 const Extension* GetExtensionForRenderViewHost(
101 content::RenderViewHost* render_view_host);
103 // Returns true if the (lazy) background host for the given extension has
104 // already been sent the unload event and is shutting down.
105 bool IsBackgroundHostClosing(const std::string& extension_id);
107 // Getter and setter for the lazy background page's keepalive count. This is
108 // the count of how many outstanding "things" are keeping the page alive.
109 // When this reaches 0, we will begin the process of shutting down the page.
110 // "Things" include pending events, resource loads, and API calls.
111 int GetLazyKeepaliveCount(const Extension* extension);
112 void IncrementLazyKeepaliveCount(const Extension* extension);
113 void DecrementLazyKeepaliveCount(const Extension* extension);
115 // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
116 // impulses will only keep the page alive for a limited amount of time unless
117 // called regularly.
118 void KeepaliveImpulse(const Extension* extension);
120 // Triggers a keepalive impulse for a plug-in (e.g NaCl).
121 static void OnKeepaliveFromPlugin(int render_process_id,
122 int render_frame_id,
123 const std::string& extension_id);
125 // Handles a response to the ShouldSuspend message, used for lazy background
126 // pages.
127 void OnShouldSuspendAck(const std::string& extension_id, uint64 sequence_id);
129 // Same as above, for the Suspend message.
130 void OnSuspendAck(const std::string& extension_id);
132 // Tracks network requests for a given RenderFrameHost, used to know
133 // when network activity is idle for lazy background pages.
134 void OnNetworkRequestStarted(content::RenderFrameHost* render_frame_host,
135 uint64 request_id);
136 void OnNetworkRequestDone(content::RenderFrameHost* render_frame_host,
137 uint64 request_id);
139 // Prevents |extension|'s background page from being closed and sends the
140 // onSuspendCanceled() event to it.
141 void CancelSuspend(const Extension* extension);
143 // Creates background hosts if the embedder is ready and they are not already
144 // loaded.
145 void MaybeCreateStartupBackgroundHosts();
147 // Called on shutdown to close our extension hosts.
148 void CloseBackgroundHosts();
150 // Gets the BrowserContext associated with site_instance_ and all other
151 // related SiteInstances.
152 content::BrowserContext* GetBrowserContext() const;
154 // Sets callbacks for testing keepalive impulse behavior.
155 typedef base::Callback<void(const std::string& extension_id)>
156 ImpulseCallbackForTesting;
157 void SetKeepaliveImpulseCallbackForTesting(
158 const ImpulseCallbackForTesting& callback);
159 void SetKeepaliveImpulseDecrementCallbackForTesting(
160 const ImpulseCallbackForTesting& callback);
162 // Sets the time in milliseconds that an extension event page can
163 // be idle before it is shut down; must be > 0.
164 static void SetEventPageIdleTimeForTesting(unsigned idle_time_msec);
166 // Sets the time in milliseconds that an extension event page has
167 // between being notified of its impending unload and that unload
168 // happening.
169 static void SetEventPageSuspendingTimeForTesting(
170 unsigned suspending_time_msec);
172 // Creates a non-incognito instance for tests. |registry| allows unit tests
173 // to inject an ExtensionRegistry that is not managed by the usual
174 // BrowserContextKeyedServiceFactory system.
175 static ProcessManager* CreateForTesting(content::BrowserContext* context,
176 ExtensionRegistry* registry);
178 // Creates an incognito-context instance for tests.
179 static ProcessManager* CreateIncognitoForTesting(
180 content::BrowserContext* incognito_context,
181 content::BrowserContext* original_context,
182 ExtensionRegistry* registry);
184 bool startup_background_hosts_created_for_test() const {
185 return startup_background_hosts_created_;
188 protected:
189 static ProcessManager* Create(content::BrowserContext* context);
191 // |context| is incognito pass the master context as |original_context|.
192 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
193 // |context| as |registry|, or override it for testing.
194 ProcessManager(content::BrowserContext* context,
195 content::BrowserContext* original_context,
196 ExtensionRegistry* registry);
198 // content::NotificationObserver:
199 void Observe(int type,
200 const content::NotificationSource& source,
201 const content::NotificationDetails& details) override;
203 content::NotificationRegistrar registrar_;
205 // The set of ExtensionHosts running viewless background extensions.
206 ExtensionHostSet background_hosts_;
208 // A SiteInstance related to the SiteInstance for all extensions in
209 // this profile. We create it in such a way that a new
210 // browsing instance is created. This controls process grouping.
211 scoped_refptr<content::SiteInstance> site_instance_;
213 // Not owned. Also used by IncognitoProcessManager.
214 ExtensionRegistry* extension_registry_;
216 private:
217 friend class ProcessManagerFactory;
218 friend class ProcessManagerTest;
220 // Extra information we keep for each extension's background page.
221 struct BackgroundPageData;
222 struct ExtensionRenderViewData;
223 typedef std::string ExtensionId;
224 typedef std::map<ExtensionId, BackgroundPageData> BackgroundPageDataMap;
225 typedef std::map<content::RenderViewHost*, ExtensionRenderViewData>
226 ExtensionRenderViews;
228 // Load all background pages once the profile data is ready and the pages
229 // should be loaded.
230 void CreateStartupBackgroundHosts();
232 // Called just after |host| is created so it can be registered in our lists.
233 void OnBackgroundHostCreated(ExtensionHost* host);
235 // Close the given |host| iff it's a background page.
236 void CloseBackgroundHost(ExtensionHost* host);
238 // Internal implementation of DecrementLazyKeepaliveCount with an
239 // |extension_id| known to have a lazy background page.
240 void DecrementLazyKeepaliveCount(const std::string& extension_id);
242 // Checks if keepalive impulses have occured, and adjusts keep alive count.
243 void OnKeepaliveImpulseCheck();
245 // These are called when the extension transitions between idle and active.
246 // They control the process of closing the background page when idle.
247 void OnLazyBackgroundPageIdle(const std::string& extension_id,
248 uint64 sequence_id);
249 void OnLazyBackgroundPageActive(const std::string& extension_id);
250 void CloseLazyBackgroundPageNow(const std::string& extension_id,
251 uint64 sequence_id);
253 // Potentially registers a RenderViewHost, if it is associated with an
254 // extension. Does nothing if this is not an extension renderer.
255 // Returns true, if render_view_host was registered (it is associated
256 // with an extension).
257 bool RegisterRenderViewHost(content::RenderViewHost* render_view_host);
259 // Unregister RenderViewHosts and clear background page data for an extension
260 // which has been unloaded.
261 void UnregisterExtension(const std::string& extension_id);
263 // Clears background page data for this extension.
264 void ClearBackgroundPageData(const std::string& extension_id);
266 void OnDevToolsStateChanged(content::DevToolsAgentHost*, bool attached);
268 // Contains all active extension-related RenderViewHost instances for all
269 // extensions. We also keep a cache of the host's view type, because that
270 // information is not accessible at registration/deregistration time.
271 ExtensionRenderViews all_extension_views_;
273 BackgroundPageDataMap background_page_data_;
275 // True if we have created the startup set of background hosts.
276 bool startup_background_hosts_created_;
278 base::Callback<void(content::DevToolsAgentHost*, bool)> devtools_callback_;
280 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_;
281 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_;
283 ObserverList<ProcessManagerObserver> observer_list_;
285 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
286 // members. These IDs are tracked per extension in background_page_data_ and
287 // are used to verify that nothing has interrupted the process of closing a
288 // lazy background process.
290 // Any interruption obtains a new ID by incrementing
291 // last_background_close_sequence_id_ and storing it in background_page_data_
292 // for a particular extension. Callbacks and round-trip IPC messages store the
293 // value of the extension's close_sequence_id at the beginning of the process.
294 // Thus comparisons can be done to halt when IDs no longer match.
296 // This counter provides unique IDs even when BackgroundPageData objects are
297 // reset.
298 uint64 last_background_close_sequence_id_;
300 // Must be last member, see doc on WeakPtrFactory.
301 base::WeakPtrFactory<ProcessManager> weak_ptr_factory_;
303 DISALLOW_COPY_AND_ASSIGN(ProcessManager);
306 } // namespace extensions
308 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_