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_
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/threading/thread_checker.h"
17 #include "base/timer/timer.h"
18 #include "build/build_config.h"
19 #include "content/child/child_thread.h"
20 #include "content/common/content_export.h"
21 #include "content/common/gpu/client/gpu_channel_host.h"
22 #include "content/public/renderer/render_thread.h"
23 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
24 #include "ipc/ipc_channel_proxy.h"
25 #include "ui/gfx/native_widget_types.h"
29 struct ViewMsg_New_Params
;
33 class WebGraphicsContext3D
;
34 class WebMediaStreamCenter
;
35 class WebMediaStreamCenterClient
;
39 class MessageLoopProxy
;
44 class ContextProvider
;
48 class ForwardingMessageFilter
;
52 class AudioHardwareConfig
;
61 class GrContextForWebGraphicsContext3D
;
67 class AppCacheDispatcher
;
68 class AudioInputMessageFilter
;
69 class AudioMessageFilter
;
70 class AudioRendererMixerManager
;
71 class ContextProviderCommandBuffer
;
72 class DBMessageFilter
;
73 class DevToolsAgentFilter
;
74 class DomStorageDispatcher
;
75 class EmbeddedWorkerDispatcher
;
76 class GamepadSharedMemoryReader
;
78 class IndexedDBDispatcher
;
79 class InputEventFilter
;
80 class InputHandlerManager
;
81 class MediaStreamCenter
;
82 class MediaStreamDependencyFactory
;
83 class MIDIMessageFilter
;
84 class P2PSocketDispatcher
;
85 class PeerConnectionTracker
;
86 class RendererDemuxerAndroid
;
87 class RendererWebKitPlatformSupportImpl
;
88 class RenderProcessObserver
;
89 class VideoCaptureImplManager
;
90 class WebGraphicsContext3DCommandBufferImpl
;
91 class WebRTCIdentityService
;
93 // The RenderThreadImpl class represents a background thread where RenderView
94 // instances live. The RenderThread supports an API that is used by its
95 // consumer to talk indirectly to the RenderViews and supporting objects.
96 // Likewise, it provides an API for the RenderViews to talk back to the main
97 // process (i.e., their corresponding WebContentsImpl).
99 // Most of the communication occurs in the form of IPC messages. They are
100 // routed to the RenderThread according to the routing IDs of the messages.
101 // The routing IDs correspond to RenderView instances.
102 class CONTENT_EXPORT RenderThreadImpl
: public RenderThread
,
104 public GpuChannelHostFactory
{
106 static RenderThreadImpl
* current();
109 // Constructor that's used when running in single process mode.
110 explicit RenderThreadImpl(const std::string
& channel_name
);
111 virtual ~RenderThreadImpl();
112 virtual void Shutdown() OVERRIDE
;
114 // When initializing WebKit, ensure that any schemes needed for the content
115 // module are registered properly. Static to allow sharing with tests.
116 static void RegisterSchemes();
118 // RenderThread implementation:
119 virtual bool Send(IPC::Message
* msg
) OVERRIDE
;
120 virtual base::MessageLoop
* GetMessageLoop() OVERRIDE
;
121 virtual IPC::SyncChannel
* GetChannel() OVERRIDE
;
122 virtual std::string
GetLocale() OVERRIDE
;
123 virtual IPC::SyncMessageFilter
* GetSyncMessageFilter() OVERRIDE
;
124 virtual scoped_refptr
<base::MessageLoopProxy
> GetIOMessageLoopProxy()
126 virtual void AddRoute(int32 routing_id
, IPC::Listener
* listener
) OVERRIDE
;
127 virtual void RemoveRoute(int32 routing_id
) OVERRIDE
;
128 virtual int GenerateRoutingID() OVERRIDE
;
129 virtual void AddFilter(IPC::ChannelProxy::MessageFilter
* filter
) OVERRIDE
;
130 virtual void RemoveFilter(IPC::ChannelProxy::MessageFilter
* filter
) OVERRIDE
;
131 virtual void AddObserver(RenderProcessObserver
* observer
) OVERRIDE
;
132 virtual void RemoveObserver(RenderProcessObserver
* observer
) OVERRIDE
;
133 virtual void SetResourceDispatcherDelegate(
134 ResourceDispatcherDelegate
* delegate
) OVERRIDE
;
135 virtual void EnsureWebKitInitialized() OVERRIDE
;
136 virtual void RecordAction(const UserMetricsAction
& action
) OVERRIDE
;
137 virtual void RecordComputedAction(const std::string
& action
) OVERRIDE
;
138 virtual scoped_ptr
<base::SharedMemory
> HostAllocateSharedMemoryBuffer(
139 size_t buffer_size
) OVERRIDE
;
140 virtual void RegisterExtension(v8::Extension
* extension
) OVERRIDE
;
141 virtual void ScheduleIdleHandler(int64 initial_delay_ms
) OVERRIDE
;
142 virtual void IdleHandler() OVERRIDE
;
143 virtual int64
GetIdleNotificationDelayInMs() const OVERRIDE
;
144 virtual void SetIdleNotificationDelayInMs(
145 int64 idle_notification_delay_in_ms
) OVERRIDE
;
146 virtual void ToggleWebKitSharedTimer(bool suspend
) OVERRIDE
;
147 virtual void UpdateHistograms(int sequence_number
) OVERRIDE
;
148 virtual int PostTaskToAllWebWorkers(const base::Closure
& closure
) OVERRIDE
;
149 virtual bool ResolveProxy(const GURL
& url
, std::string
* proxy_list
) OVERRIDE
;
151 virtual void PreCacheFont(const LOGFONT
& log_font
) OVERRIDE
;
152 virtual void ReleaseCachedFonts() OVERRIDE
;
155 // Synchronously establish a channel to the GPU plugin if not previously
156 // established or if it has been lost (for example if the GPU plugin crashed).
157 // If there is a pending asynchronous request, it will be completed by the
158 // time this routine returns.
159 GpuChannelHost
* EstablishGpuChannelSync(CauseForGpuLaunch
);
162 // These methods modify how the next message is sent. Normally, when sending
163 // a synchronous message that runs a nested message loop, we need to suspend
164 // callbacks into WebKit. This involves disabling timers and deferring
165 // resource loads. However, there are exceptions when we need to customize
167 void DoNotSuspendWebKitSharedTimer();
168 void DoNotNotifyWebKitOfModalLoop();
170 // True if we are running layout tests. This currently disables forwarding
171 // various status messages to the console, skips network error pages, and
172 // short circuits size update and focus events.
173 bool layout_test_mode() const {
174 return layout_test_mode_
;
176 void set_layout_test_mode(bool layout_test_mode
) {
177 layout_test_mode_
= layout_test_mode
;
180 IPC::ForwardingMessageFilter
* compositor_output_surface_filter() const {
181 return compositor_output_surface_filter_
.get();
184 InputHandlerManager
* input_handler_manager() const {
185 return input_handler_manager_
.get();
188 // Will be NULL if threaded compositing has not been enabled.
189 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy() const {
190 return compositor_message_loop_proxy_
;
193 AppCacheDispatcher
* appcache_dispatcher() const {
194 return appcache_dispatcher_
.get();
197 DomStorageDispatcher
* dom_storage_dispatcher() const {
198 return dom_storage_dispatcher_
.get();
201 EmbeddedWorkerDispatcher
* embedded_worker_dispatcher() const {
202 return embedded_worker_dispatcher_
.get();
205 AudioInputMessageFilter
* audio_input_message_filter() {
206 return audio_input_message_filter_
.get();
209 AudioMessageFilter
* audio_message_filter() {
210 return audio_message_filter_
.get();
213 MIDIMessageFilter
* midi_message_filter() {
214 return midi_message_filter_
.get();
217 #if defined(OS_ANDROID)
218 RendererDemuxerAndroid
* renderer_demuxer() {
219 return renderer_demuxer_
.get();
223 // Creates the embedder implementation of WebMediaStreamCenter.
224 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
225 blink::WebMediaStreamCenter
* CreateMediaStreamCenter(
226 blink::WebMediaStreamCenterClient
* client
);
228 // Returns a factory used for creating RTC PeerConnection objects.
229 MediaStreamDependencyFactory
* GetMediaStreamDependencyFactory();
231 PeerConnectionTracker
* peer_connection_tracker() {
232 return peer_connection_tracker_
.get();
235 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
236 P2PSocketDispatcher
* p2p_socket_dispatcher() {
237 return p2p_socket_dispatcher_
.get();
240 VideoCaptureImplManager
* video_capture_impl_manager() const {
241 return vc_manager_
.get();
244 // Get the GPU channel. Returns NULL if the channel is not established or
246 GpuChannelHost
* GetGpuChannel();
248 // Returns a MessageLoopProxy instance corresponding to the message loop
249 // of the thread on which file operations should be run. Must be called
250 // on the renderer's main thread.
251 scoped_refptr
<base::MessageLoopProxy
> GetFileThreadMessageLoopProxy();
253 // Returns a MessageLoopProxy instance corresponding to the message loop
254 // of the thread on which media operations should be run. Must be called
255 // on the renderer's main thread.
256 scoped_refptr
<base::MessageLoopProxy
> GetMediaThreadMessageLoopProxy();
258 // Causes the idle handler to skip sending idle notifications
259 // on the two next scheduled calls, so idle notifications are
260 // not sent for at least one notification delay.
261 void PostponeIdleNotification();
263 scoped_refptr
<RendererGpuVideoAcceleratorFactories
> GetGpuFactories();
265 scoped_refptr
<cc::ContextProvider
> OffscreenCompositorContextProvider();
266 scoped_refptr
<cc::ContextProvider
> SharedMainThreadContextProvider();
268 // AudioRendererMixerManager instance which manages renderer side mixer
269 // instances shared based on configured audio parameters. Lazily created on
271 AudioRendererMixerManager
* GetAudioRendererMixerManager();
273 // AudioHardwareConfig contains audio hardware configuration for
274 // renderer side clients. Creation requires a synchronous IPC call so it is
275 // lazily created on the first call.
276 media::AudioHardwareConfig
* GetAudioHardwareConfig();
279 void PreCacheFontCharacters(const LOGFONT
& log_font
,
280 const base::string16
& str
);
283 #if defined(ENABLE_WEBRTC)
284 WebRTCIdentityService
* get_webrtc_identity_service() {
285 return webrtc_identity_service_
.get();
289 // For producing custom V8 histograms. Custom histograms are produced if all
290 // RenderViews share the same host, and the host is in the pre-specified set
291 // of hosts we want to produce custom diagrams for. The name for a custom
292 // diagram is the name of the corresponding generic diagram plus a
293 // host-specific suffix.
294 class CONTENT_EXPORT HistogramCustomizer
{
296 HistogramCustomizer();
297 ~HistogramCustomizer();
299 // Called when a top frame of a RenderView navigates. This function updates
300 // RenderThreadImpl's information about whether all RenderViews are
301 // displaying a page from the same host. |host| is the host where a
302 // RenderView navigated, and |view_count| is the number of RenderViews in
304 void RenderViewNavigatedToHost(const std::string
& host
, size_t view_count
);
306 // Used for customizing some histograms if all RenderViews share the same
307 // host. Returns the current custom histogram name to use for
308 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
309 std::string
ConvertToCustomHistogramName(const char* histogram_name
) const;
312 friend class RenderThreadImplUnittest
;
314 // Used for updating the information on which is the common host which all
315 // RenderView's share (if any). If there is no common host, this function is
316 // called with an empty string.
317 void SetCommonHost(const std::string
& host
);
319 // The current common host of the RenderViews; empty string if there is no
321 std::string common_host_
;
322 // The corresponding suffix.
323 std::string common_host_histogram_suffix_
;
324 // Set of histograms for which we want to produce a custom histogram if
326 std::set
<std::string
> custom_histograms_
;
328 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer
);
331 HistogramCustomizer
* histogram_customizer() {
332 return &histogram_customizer_
;
335 void SetFlingCurveParameters(const std::vector
<float>& new_touchpad
,
336 const std::vector
<float>& new_touchscreen
);
338 // Retrieve current gamepad data.
339 void SampleGamepads(blink::WebGamepads
* data
);
341 // Get the browser process's notion of the renderer process's ID.
342 // This is the first argument to RenderWidgetHost::FromID. Ideally
343 // this would be available on all platforms via base::Process.
344 base::ProcessId
renderer_process_id() const;
346 // Called by a RenderWidget when it is created or destroyed. This
347 // allows the process to know when there are no visible widgets.
348 void WidgetCreated();
349 void WidgetDestroyed();
351 void WidgetRestored();
355 virtual bool OnControlMessageReceived(const IPC::Message
& msg
) OVERRIDE
;
357 // GpuChannelHostFactory implementation:
358 virtual bool IsMainThread() OVERRIDE
;
359 virtual base::MessageLoop
* GetMainLoop() OVERRIDE
;
360 virtual scoped_refptr
<base::MessageLoopProxy
> GetIOLoopProxy() OVERRIDE
;
361 virtual base::WaitableEvent
* GetShutDownEvent() OVERRIDE
;
362 virtual scoped_ptr
<base::SharedMemory
> AllocateSharedMemory(
363 size_t size
) OVERRIDE
;
364 virtual int32
CreateViewCommandBuffer(
366 const GPUCreateCommandBufferConfig
& init_params
) OVERRIDE
;
367 virtual void CreateImage(
368 gfx::PluginWindowHandle window
,
370 const CreateImageCallback
& callback
) OVERRIDE
;
371 virtual void DeleteImage(int32 image_id
, int32 sync_point
) OVERRIDE
;
372 virtual scoped_ptr
<gfx::GpuMemoryBuffer
> AllocateGpuMemoryBuffer(
375 unsigned internalformat
) OVERRIDE
;
379 void OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
380 const std::string
& host
,
382 void OnCreateNewView(const ViewMsg_New_Params
& params
);
383 void OnTransferBitmap(const SkBitmap
& bitmap
, int resource_id
);
384 void OnPurgePluginListCache(bool reload_pages
);
385 void OnNetworkStateChanged(bool online
);
386 void OnGetAccessibilityTree();
387 void OnTempCrashWithData(const GURL
& data
);
388 void OnSetRendererProcessID(base::ProcessId process_id
);
389 void OnMemoryPressure(
390 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
391 #if defined(OS_ANDROID)
392 void OnSetWebKitSharedTimersSuspended(bool suspend
);
394 #if defined(OS_MACOSX)
395 void OnUpdateScrollbarTheme(float initial_button_delay
,
396 float autoscroll_button_delay
,
397 bool jump_on_track_click
,
401 void IdleHandlerInForegroundTab();
403 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
> CreateOffscreenContext3d();
405 // These objects live solely on the render thread.
406 scoped_ptr
<AppCacheDispatcher
> appcache_dispatcher_
;
407 scoped_ptr
<DomStorageDispatcher
> dom_storage_dispatcher_
;
408 scoped_ptr
<IndexedDBDispatcher
> main_thread_indexed_db_dispatcher_
;
409 scoped_ptr
<RendererWebKitPlatformSupportImpl
> webkit_platform_support_
;
410 scoped_ptr
<EmbeddedWorkerDispatcher
> embedded_worker_dispatcher_
;
412 // Used on the render thread and deleted by WebKit at shutdown.
413 blink::WebMediaStreamCenter
* media_stream_center_
;
415 // Used on the renderer and IPC threads.
416 scoped_refptr
<DBMessageFilter
> db_message_filter_
;
417 scoped_refptr
<AudioInputMessageFilter
> audio_input_message_filter_
;
418 scoped_refptr
<AudioMessageFilter
> audio_message_filter_
;
419 scoped_refptr
<MIDIMessageFilter
> midi_message_filter_
;
420 #if defined(OS_ANDROID)
421 scoped_refptr
<RendererDemuxerAndroid
> renderer_demuxer_
;
423 scoped_refptr
<DevToolsAgentFilter
> devtools_agent_message_filter_
;
425 scoped_ptr
<MediaStreamDependencyFactory
> media_stream_factory_
;
427 // This is used to communicate to the browser process the status
428 // of all the peer connections created in the renderer.
429 scoped_ptr
<PeerConnectionTracker
> peer_connection_tracker_
;
431 // Dispatches all P2P sockets.
432 scoped_refptr
<P2PSocketDispatcher
> p2p_socket_dispatcher_
;
434 // Used on the render thread.
435 scoped_ptr
<VideoCaptureImplManager
> vc_manager_
;
437 // The count of RenderWidgets running through this thread.
440 // The count of hidden RenderWidgets running through this thread.
441 int hidden_widget_count_
;
443 // The current value of the idle notification timer delay.
444 int64 idle_notification_delay_in_ms_
;
446 // The number of idle handler calls that skip sending idle notifications.
447 int idle_notifications_to_skip_
;
449 bool suspend_webkit_shared_timer_
;
450 bool notify_webkit_of_modal_loop_
;
452 // The following flag is used to control layout test specific behavior.
453 bool layout_test_mode_
;
455 // Timer that periodically calls IdleHandler.
456 base::RepeatingTimer
<RenderThreadImpl
> idle_timer_
;
458 // The channel from the renderer process to the GPU process.
459 scoped_refptr
<GpuChannelHost
> gpu_channel_
;
461 // Cache of variables that are needed on the compositor thread by
462 // GpuChannelHostFactory methods.
463 scoped_refptr
<base::MessageLoopProxy
> io_message_loop_proxy_
;
464 base::WaitableEvent
* shutdown_event_
;
466 // A lazily initiated thread on which file operations are run.
467 scoped_ptr
<base::Thread
> file_thread_
;
469 // May be null if overridden by ContentRendererClient.
470 scoped_ptr
<base::Thread
> compositor_thread_
;
472 // Thread for running multimedia operations (e.g., video decoding).
473 scoped_ptr
<base::Thread
> media_thread_
;
475 // Will point to appropriate MessageLoopProxy after initialization,
476 // regardless of whether |compositor_thread_| is overriden.
477 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy_
;
479 // May be null if unused by the |input_handler_manager_|.
480 scoped_refptr
<InputEventFilter
> input_event_filter_
;
481 scoped_ptr
<InputHandlerManager
> input_handler_manager_
;
482 scoped_refptr
<IPC::ForwardingMessageFilter
> compositor_output_surface_filter_
;
484 scoped_refptr
<ContextProviderCommandBuffer
> offscreen_compositor_contexts_
;
485 scoped_refptr
<ContextProviderCommandBuffer
> shared_main_thread_contexts_
;
487 ObserverList
<RenderProcessObserver
> observers_
;
489 scoped_refptr
<ContextProviderCommandBuffer
> gpu_va_context_provider_
;
491 scoped_ptr
<AudioRendererMixerManager
> audio_renderer_mixer_manager_
;
492 scoped_ptr
<media::AudioHardwareConfig
> audio_hardware_config_
;
494 HistogramCustomizer histogram_customizer_
;
496 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
498 scoped_ptr
<WebRTCIdentityService
> webrtc_identity_service_
;
500 scoped_ptr
<GamepadSharedMemoryReader
> gamepad_shared_memory_reader_
;
502 base::ProcessId renderer_process_id_
;
504 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
505 // multiple threads. Current allocation mechanism for IOSurface
506 // backed GpuMemoryBuffers prevent this. crbug.com/325045
507 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_
;
509 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl
);
512 } // namespace content
514 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_