Refactor management of overview window copy lifetime into a separate class.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.h
blobb0c0317334392e03d32f81d486beb590e032ad21
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.
5 #ifndef CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
6 #define CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
8 #include <set>
9 #include <string>
10 #include <vector>
12 #include "base/memory/memory_pressure_listener.h"
13 #include "base/observer_list.h"
14 #include "base/process/process_handle.h"
15 #include "base/strings/string16.h"
16 #include "base/timer/timer.h"
17 #include "build/build_config.h"
18 #include "content/child/child_thread.h"
19 #include "content/common/content_export.h"
20 #include "content/common/gpu/client/gpu_channel_host.h"
21 #include "content/public/renderer/render_thread.h"
22 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
23 #include "ipc/ipc_channel_proxy.h"
24 #include "ui/gfx/native_widget_types.h"
26 class GrContext;
27 class SkBitmap;
28 struct ViewMsg_New_Params;
30 namespace WebKit {
31 class WebGamepads;
32 class WebGraphicsContext3D;
33 class WebMediaStreamCenter;
34 class WebMediaStreamCenterClient;
37 namespace base {
38 class MessageLoopProxy;
39 class Thread;
41 #if defined(OS_WIN)
42 namespace win {
43 class ScopedCOMInitializer;
45 #endif
48 namespace cc {
49 class ContextProvider;
52 namespace IPC {
53 class ForwardingMessageFilter;
56 namespace media {
57 class AudioHardwareConfig;
60 namespace v8 {
61 class Extension;
64 namespace webkit {
65 namespace gpu {
66 class GrContextForWebGraphicsContext3D;
70 namespace content {
72 class AppCacheDispatcher;
73 class AudioInputMessageFilter;
74 class AudioMessageFilter;
75 class AudioRendererMixerManager;
76 class ContextProviderCommandBuffer;
77 class DBMessageFilter;
78 class DevToolsAgentFilter;
79 class DomStorageDispatcher;
80 class GamepadSharedMemoryReader;
81 class GpuChannelHost;
82 class IndexedDBDispatcher;
83 class InputEventFilter;
84 class InputHandlerManager;
85 class MediaStreamCenter;
86 class MediaStreamDependencyFactory;
87 class MIDIMessageFilter;
88 class P2PSocketDispatcher;
89 class PeerConnectionTracker;
90 class RendererDemuxerAndroid;
91 class RendererWebKitPlatformSupportImpl;
92 class RenderProcessObserver;
93 class VideoCaptureImplManager;
94 class WebDatabaseObserverImpl;
95 class WebGraphicsContext3DCommandBufferImpl;
96 class WebRTCIdentityService;
98 // The RenderThreadImpl class represents a background thread where RenderView
99 // instances live. The RenderThread supports an API that is used by its
100 // consumer to talk indirectly to the RenderViews and supporting objects.
101 // Likewise, it provides an API for the RenderViews to talk back to the main
102 // process (i.e., their corresponding WebContentsImpl).
104 // Most of the communication occurs in the form of IPC messages. They are
105 // routed to the RenderThread according to the routing IDs of the messages.
106 // The routing IDs correspond to RenderView instances.
107 class CONTENT_EXPORT RenderThreadImpl : public RenderThread,
108 public ChildThread,
109 public GpuChannelHostFactory {
110 public:
111 static RenderThreadImpl* current();
113 RenderThreadImpl();
114 // Constructor that's used when running in single process mode.
115 explicit RenderThreadImpl(const std::string& channel_name);
116 virtual ~RenderThreadImpl();
117 virtual void Shutdown() OVERRIDE;
119 // When initializing WebKit, ensure that any schemes needed for the content
120 // module are registered properly. Static to allow sharing with tests.
121 static void RegisterSchemes();
123 // RenderThread implementation:
124 virtual bool Send(IPC::Message* msg) OVERRIDE;
125 virtual base::MessageLoop* GetMessageLoop() OVERRIDE;
126 virtual IPC::SyncChannel* GetChannel() OVERRIDE;
127 virtual std::string GetLocale() OVERRIDE;
128 virtual IPC::SyncMessageFilter* GetSyncMessageFilter() OVERRIDE;
129 virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy()
130 OVERRIDE;
131 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
132 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
133 virtual int GenerateRoutingID() OVERRIDE;
134 virtual void AddFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
135 virtual void RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
136 virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
137 virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
138 virtual void SetResourceDispatcherDelegate(
139 ResourceDispatcherDelegate* delegate) OVERRIDE;
140 virtual void WidgetHidden() OVERRIDE;
141 virtual void WidgetRestored() OVERRIDE;
142 virtual void EnsureWebKitInitialized() OVERRIDE;
143 virtual void RecordUserMetrics(const std::string& action) OVERRIDE;
144 virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
145 size_t buffer_size) OVERRIDE;
146 virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
147 virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
148 virtual void IdleHandler() OVERRIDE;
149 virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
150 virtual void SetIdleNotificationDelayInMs(
151 int64 idle_notification_delay_in_ms) OVERRIDE;
152 virtual void ToggleWebKitSharedTimer(bool suspend) OVERRIDE;
153 virtual void UpdateHistograms(int sequence_number) OVERRIDE;
154 virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
155 virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
156 #if defined(OS_WIN)
157 virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
158 virtual void ReleaseCachedFonts() OVERRIDE;
159 #endif
161 // Synchronously establish a channel to the GPU plugin if not previously
162 // established or if it has been lost (for example if the GPU plugin crashed).
163 // If there is a pending asynchronous request, it will be completed by the
164 // time this routine returns.
165 GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
168 // These methods modify how the next message is sent. Normally, when sending
169 // a synchronous message that runs a nested message loop, we need to suspend
170 // callbacks into WebKit. This involves disabling timers and deferring
171 // resource loads. However, there are exceptions when we need to customize
172 // the behavior.
173 void DoNotSuspendWebKitSharedTimer();
174 void DoNotNotifyWebKitOfModalLoop();
176 // True if we are running layout tests. This currently disables forwarding
177 // various status messages to the console, skips network error pages, and
178 // short circuits size update and focus events.
179 bool layout_test_mode() const {
180 return layout_test_mode_;
182 void set_layout_test_mode(bool layout_test_mode) {
183 layout_test_mode_ = layout_test_mode;
186 IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
187 return compositor_output_surface_filter_.get();
190 InputHandlerManager* input_handler_manager() const {
191 return input_handler_manager_.get();
194 // Will be NULL if threaded compositing has not been enabled.
195 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
196 return compositor_message_loop_proxy_;
199 AppCacheDispatcher* appcache_dispatcher() const {
200 return appcache_dispatcher_.get();
203 DomStorageDispatcher* dom_storage_dispatcher() const {
204 return dom_storage_dispatcher_.get();
207 AudioInputMessageFilter* audio_input_message_filter() {
208 return audio_input_message_filter_.get();
211 AudioMessageFilter* audio_message_filter() {
212 return audio_message_filter_.get();
215 MIDIMessageFilter* midi_message_filter() {
216 return midi_message_filter_.get();
219 #if defined(OS_ANDROID)
220 RendererDemuxerAndroid* renderer_demuxer() {
221 return renderer_demuxer_.get();
223 #endif
225 // Creates the embedder implementation of WebMediaStreamCenter.
226 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
227 WebKit::WebMediaStreamCenter* CreateMediaStreamCenter(
228 WebKit::WebMediaStreamCenterClient* client);
230 // Returns a factory used for creating RTC PeerConnection objects.
231 MediaStreamDependencyFactory* GetMediaStreamDependencyFactory();
233 PeerConnectionTracker* peer_connection_tracker() {
234 return peer_connection_tracker_.get();
237 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
238 P2PSocketDispatcher* p2p_socket_dispatcher() {
239 return p2p_socket_dispatcher_.get();
242 VideoCaptureImplManager* video_capture_impl_manager() const {
243 return vc_manager_.get();
246 // Get the GPU channel. Returns NULL if the channel is not established or
247 // has been lost.
248 GpuChannelHost* GetGpuChannel();
250 // Returns a MessageLoopProxy instance corresponding to the message loop
251 // of the thread on which file operations should be run. Must be called
252 // on the renderer's main thread.
253 scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
255 // Returns a MessageLoopProxy instance corresponding to the message loop
256 // of the thread on which media operations should be run. Must be called
257 // on the renderer's main thread.
258 scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
260 // Causes the idle handler to skip sending idle notifications
261 // on the two next scheduled calls, so idle notifications are
262 // not sent for at least one notification delay.
263 void PostponeIdleNotification();
265 scoped_refptr<RendererGpuVideoAcceleratorFactories> GetGpuFactories();
267 scoped_refptr<cc::ContextProvider> OffscreenCompositorContextProvider();
268 scoped_refptr<cc::ContextProvider> SharedMainThreadContextProvider();
270 // AudioRendererMixerManager instance which manages renderer side mixer
271 // instances shared based on configured audio parameters. Lazily created on
272 // first call.
273 AudioRendererMixerManager* GetAudioRendererMixerManager();
275 // AudioHardwareConfig contains audio hardware configuration for
276 // renderer side clients. Creation requires a synchronous IPC call so it is
277 // lazily created on the first call.
278 media::AudioHardwareConfig* GetAudioHardwareConfig();
280 #if defined(OS_WIN)
281 void PreCacheFontCharacters(const LOGFONT& log_font, const string16& str);
282 #endif
284 #if defined(ENABLE_WEBRTC)
285 WebRTCIdentityService* get_webrtc_identity_service() {
286 return webrtc_identity_service_.get();
288 #endif
290 // For producing custom V8 histograms. Custom histograms are produced if all
291 // RenderViews share the same host, and the host is in the pre-specified set
292 // of hosts we want to produce custom diagrams for. The name for a custom
293 // diagram is the name of the corresponding generic diagram plus a
294 // host-specific suffix.
295 class CONTENT_EXPORT HistogramCustomizer {
296 public:
297 HistogramCustomizer();
298 ~HistogramCustomizer();
300 // Called when a top frame of a RenderView navigates. This function updates
301 // RenderThreadImpl's information about whether all RenderViews are
302 // displaying a page from the same host. |host| is the host where a
303 // RenderView navigated, and |view_count| is the number of RenderViews in
304 // this process.
305 void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
307 // Used for customizing some histograms if all RenderViews share the same
308 // host. Returns the current custom histogram name to use for
309 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
310 std::string ConvertToCustomHistogramName(const char* histogram_name) const;
312 private:
313 friend class RenderThreadImplUnittest;
315 // Used for updating the information on which is the common host which all
316 // RenderView's share (if any). If there is no common host, this function is
317 // called with an empty string.
318 void SetCommonHost(const std::string& host);
320 // The current common host of the RenderViews; empty string if there is no
321 // common host.
322 std::string common_host_;
323 // The corresponding suffix.
324 std::string common_host_histogram_suffix_;
325 // Set of histograms for which we want to produce a custom histogram if
326 // possible.
327 std::set<std::string> custom_histograms_;
329 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
332 HistogramCustomizer* histogram_customizer() {
333 return &histogram_customizer_;
336 void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
337 const std::vector<float>& new_touchscreen);
339 // Retrieve current gamepad data.
340 void SampleGamepads(WebKit::WebGamepads* data);
342 // Get the browser process's notion of the renderer process's ID.
343 // This is the first argument to RenderWidgetHost::FromID. Ideally
344 // this would be available on all platforms via base::Process.
345 base::ProcessId renderer_process_id() const;
347 private:
348 // ChildThread
349 virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
351 // GpuChannelHostFactory implementation:
352 virtual bool IsMainThread() OVERRIDE;
353 virtual base::MessageLoop* GetMainLoop() OVERRIDE;
354 virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
355 virtual base::WaitableEvent* GetShutDownEvent() OVERRIDE;
356 virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
357 size_t size) OVERRIDE;
358 virtual int32 CreateViewCommandBuffer(
359 int32 surface_id,
360 const GPUCreateCommandBufferConfig& init_params) OVERRIDE;
361 virtual void CreateImage(
362 gfx::PluginWindowHandle window,
363 int32 image_id,
364 const CreateImageCallback& callback) OVERRIDE;
365 virtual void DeleteImage(int32 image_id, int32 sync_point) OVERRIDE;
366 virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
367 size_t width,
368 size_t height,
369 unsigned internalformat) OVERRIDE;
371 void Init();
373 void OnSetZoomLevelForCurrentURL(const std::string& scheme,
374 const std::string& host,
375 double zoom_level);
376 void OnCreateNewView(const ViewMsg_New_Params& params);
377 void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
378 void OnPurgePluginListCache(bool reload_pages);
379 void OnNetworkStateChanged(bool online);
380 void OnGetAccessibilityTree();
381 void OnTempCrashWithData(const GURL& data);
382 void OnSetRendererProcessID(base::ProcessId process_id);
383 void OnSetWebKitSharedTimersSuspended(bool suspend);
384 void OnMemoryPressure(
385 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
387 void IdleHandlerInForegroundTab();
389 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
391 // These objects live solely on the render thread.
392 scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
393 scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
394 scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
395 scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
397 // Used on the render thread and deleted by WebKit at shutdown.
398 WebKit::WebMediaStreamCenter* media_stream_center_;
400 // Used on the renderer and IPC threads.
401 scoped_refptr<DBMessageFilter> db_message_filter_;
402 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
403 scoped_refptr<AudioMessageFilter> audio_message_filter_;
404 scoped_refptr<MIDIMessageFilter> midi_message_filter_;
405 #if defined(OS_ANDROID)
406 scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
407 #endif
408 scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
410 scoped_ptr<MediaStreamDependencyFactory> media_stream_factory_;
412 // This is used to communicate to the browser process the status
413 // of all the peer connections created in the renderer.
414 scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
416 // Dispatches all P2P sockets.
417 scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
419 // Used on multiple threads.
420 scoped_refptr<VideoCaptureImplManager> vc_manager_;
422 // Used on multiple script execution context threads.
423 scoped_ptr<WebDatabaseObserverImpl> web_database_observer_impl_;
425 #if defined(OS_WIN)
426 // Initialize COM when using plugins outside the sandbox.
427 scoped_ptr<base::win::ScopedCOMInitializer> initialize_com_;
428 #endif
430 // The count of RenderWidgets running through this thread.
431 int widget_count_;
433 // The count of hidden RenderWidgets running through this thread.
434 int hidden_widget_count_;
436 // The current value of the idle notification timer delay.
437 int64 idle_notification_delay_in_ms_;
439 // The number of idle handler calls that skip sending idle notifications.
440 int idle_notifications_to_skip_;
442 bool suspend_webkit_shared_timer_;
443 bool notify_webkit_of_modal_loop_;
445 // The following flag is used to control layout test specific behavior.
446 bool layout_test_mode_;
448 // Timer that periodically calls IdleHandler.
449 base::RepeatingTimer<RenderThreadImpl> idle_timer_;
451 // The channel from the renderer process to the GPU process.
452 scoped_refptr<GpuChannelHost> gpu_channel_;
454 // Cache of variables that are needed on the compositor thread by
455 // GpuChannelHostFactory methods.
456 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
457 base::WaitableEvent* shutdown_event_;
459 // A lazily initiated thread on which file operations are run.
460 scoped_ptr<base::Thread> file_thread_;
462 // May be null if overridden by ContentRendererClient.
463 scoped_ptr<base::Thread> compositor_thread_;
465 // Thread for running multimedia operations (e.g., video decoding).
466 scoped_ptr<base::Thread> media_thread_;
468 // Will point to appropriate MessageLoopProxy after initialization,
469 // regardless of whether |compositor_thread_| is overriden.
470 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
472 // May be null if unused by the |input_handler_manager_|.
473 scoped_refptr<InputEventFilter> input_event_filter_;
474 scoped_ptr<InputHandlerManager> input_handler_manager_;
475 scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
477 scoped_refptr<ContextProviderCommandBuffer> offscreen_compositor_contexts_;
478 scoped_refptr<ContextProviderCommandBuffer> shared_main_thread_contexts_;
480 ObserverList<RenderProcessObserver> observers_;
482 scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
484 scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
485 scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
487 HistogramCustomizer histogram_customizer_;
489 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
491 scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
493 scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
495 base::ProcessId renderer_process_id_;
497 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
500 } // namespace content
502 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_