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/metrics/user_metrics_action.h"
14 #include "base/observer_list.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 "net/base/network_change_notifier.h"
24 #include "third_party/WebKit/public/platform/WebConnectionType.h"
25 #include "ui/gfx/native_widget_types.h"
27 #if defined(OS_MACOSX)
28 #include "third_party/WebKit/public/web/mac/WebScrollbarTheme.h"
33 struct ViewMsg_New_Params
;
34 struct WorkerProcessMsg_CreateWorker_Params
;
38 class WebGamepadListener
;
39 class WebGraphicsContext3D
;
40 class WebMediaStreamCenter
;
41 class WebMediaStreamCenterClient
;
45 class MessageLoopProxy
;
50 class ContextProvider
;
54 class ForwardingMessageFilter
;
59 class AudioHardwareConfig
;
60 class GpuVideoAcceleratorFactories
;
69 class ContextProviderWebContext
;
70 class GrContextForWebGraphicsContext3D
;
76 class AppCacheDispatcher
;
77 class AudioInputMessageFilter
;
78 class AudioMessageFilter
;
79 class AudioRendererMixerManager
;
80 class ContextProviderCommandBuffer
;
81 class DBMessageFilter
;
82 class DevToolsAgentFilter
;
83 class DomStorageDispatcher
;
84 class EmbeddedWorkerDispatcher
;
85 class GamepadSharedMemoryReader
;
87 class IndexedDBDispatcher
;
88 class InputEventFilter
;
89 class InputHandlerManager
;
90 class MediaStreamCenter
;
91 class PeerConnectionDependencyFactory
;
92 class MidiMessageFilter
;
93 class NetInfoDispatcher
;
94 class P2PSocketDispatcher
;
95 class PeerConnectionTracker
;
96 class RendererDemuxerAndroid
;
97 class RendererWebKitPlatformSupportImpl
;
98 class RenderProcessObserver
;
99 class VideoCaptureImplManager
;
100 class WebGraphicsContext3DCommandBufferImpl
;
101 class WebRTCIdentityService
;
103 // The RenderThreadImpl class represents a background thread where RenderView
104 // instances live. The RenderThread supports an API that is used by its
105 // consumer to talk indirectly to the RenderViews and supporting objects.
106 // Likewise, it provides an API for the RenderViews to talk back to the main
107 // process (i.e., their corresponding WebContentsImpl).
109 // Most of the communication occurs in the form of IPC messages. They are
110 // routed to the RenderThread according to the routing IDs of the messages.
111 // The routing IDs correspond to RenderView instances.
112 class CONTENT_EXPORT RenderThreadImpl
: public RenderThread
,
114 public GpuChannelHostFactory
{
116 static RenderThreadImpl
* current();
119 // Constructor that's used when running in single process mode.
120 explicit RenderThreadImpl(const std::string
& channel_name
);
121 virtual ~RenderThreadImpl();
122 virtual void Shutdown() OVERRIDE
;
124 // When initializing WebKit, ensure that any schemes needed for the content
125 // module are registered properly. Static to allow sharing with tests.
126 static void RegisterSchemes();
128 // Notify V8 that the date/time configuration of the system might have
130 static void NotifyTimezoneChange();
132 // RenderThread implementation:
133 virtual bool Send(IPC::Message
* msg
) OVERRIDE
;
134 virtual base::MessageLoop
* GetMessageLoop() OVERRIDE
;
135 virtual IPC::SyncChannel
* GetChannel() OVERRIDE
;
136 virtual std::string
GetLocale() OVERRIDE
;
137 virtual IPC::SyncMessageFilter
* GetSyncMessageFilter() OVERRIDE
;
138 virtual scoped_refptr
<base::MessageLoopProxy
> GetIOMessageLoopProxy()
140 virtual void AddRoute(int32 routing_id
, IPC::Listener
* listener
) OVERRIDE
;
141 virtual void RemoveRoute(int32 routing_id
) OVERRIDE
;
142 virtual int GenerateRoutingID() OVERRIDE
;
143 virtual void AddFilter(IPC::MessageFilter
* filter
) OVERRIDE
;
144 virtual void RemoveFilter(IPC::MessageFilter
* filter
) OVERRIDE
;
145 virtual void AddObserver(RenderProcessObserver
* observer
) OVERRIDE
;
146 virtual void RemoveObserver(RenderProcessObserver
* observer
) OVERRIDE
;
147 virtual void SetResourceDispatcherDelegate(
148 ResourceDispatcherDelegate
* delegate
) OVERRIDE
;
149 virtual void EnsureWebKitInitialized() OVERRIDE
;
150 virtual void RecordAction(const base::UserMetricsAction
& action
) OVERRIDE
;
151 virtual void RecordComputedAction(const std::string
& action
) OVERRIDE
;
152 virtual scoped_ptr
<base::SharedMemory
> HostAllocateSharedMemoryBuffer(
153 size_t buffer_size
) OVERRIDE
;
154 virtual void RegisterExtension(v8::Extension
* extension
) OVERRIDE
;
155 virtual void ScheduleIdleHandler(int64 initial_delay_ms
) OVERRIDE
;
156 virtual void IdleHandler() OVERRIDE
;
157 virtual int64
GetIdleNotificationDelayInMs() const OVERRIDE
;
158 virtual void SetIdleNotificationDelayInMs(
159 int64 idle_notification_delay_in_ms
) OVERRIDE
;
160 virtual void UpdateHistograms(int sequence_number
) OVERRIDE
;
161 virtual int PostTaskToAllWebWorkers(const base::Closure
& closure
) OVERRIDE
;
162 virtual bool ResolveProxy(const GURL
& url
, std::string
* proxy_list
) OVERRIDE
;
163 virtual base::WaitableEvent
* GetShutdownEvent() OVERRIDE
;
165 virtual void PreCacheFont(const LOGFONT
& log_font
) OVERRIDE
;
166 virtual void ReleaseCachedFonts() OVERRIDE
;
169 // Synchronously establish a channel to the GPU plugin if not previously
170 // established or if it has been lost (for example if the GPU plugin crashed).
171 // If there is a pending asynchronous request, it will be completed by the
172 // time this routine returns.
173 GpuChannelHost
* EstablishGpuChannelSync(CauseForGpuLaunch
);
176 // These methods modify how the next message is sent. Normally, when sending
177 // a synchronous message that runs a nested message loop, we need to suspend
178 // callbacks into WebKit. This involves disabling timers and deferring
179 // resource loads. However, there are exceptions when we need to customize
181 void DoNotSuspendWebKitSharedTimer();
182 void DoNotNotifyWebKitOfModalLoop();
184 // True if we are running layout tests. This currently disables forwarding
185 // various status messages to the console, skips network error pages, and
186 // short circuits size update and focus events.
187 bool layout_test_mode() const {
188 return layout_test_mode_
;
190 void set_layout_test_mode(bool layout_test_mode
) {
191 layout_test_mode_
= layout_test_mode
;
194 IPC::ForwardingMessageFilter
* compositor_output_surface_filter() const {
195 return compositor_output_surface_filter_
.get();
198 InputHandlerManager
* input_handler_manager() const {
199 return input_handler_manager_
.get();
202 // Will be NULL if threaded compositing has not been enabled.
203 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy() const {
204 return compositor_message_loop_proxy_
;
207 bool is_gpu_rasterization_enabled() const {
208 return is_gpu_rasterization_enabled_
;
211 bool is_gpu_rasterization_forced() const {
212 return is_gpu_rasterization_forced_
;
215 bool is_impl_side_painting_enabled() const {
216 return is_impl_side_painting_enabled_
;
219 bool is_low_res_tiling_enabled() const { return is_low_res_tiling_enabled_
; }
221 bool is_lcd_text_enabled() const { return is_lcd_text_enabled_
; }
223 bool is_distance_field_text_enabled() const {
224 return is_distance_field_text_enabled_
;
227 bool is_zero_copy_enabled() const { return is_zero_copy_enabled_
; }
229 bool is_one_copy_enabled() const { return is_one_copy_enabled_
; }
231 AppCacheDispatcher
* appcache_dispatcher() const {
232 return appcache_dispatcher_
.get();
235 DomStorageDispatcher
* dom_storage_dispatcher() const {
236 return dom_storage_dispatcher_
.get();
239 EmbeddedWorkerDispatcher
* embedded_worker_dispatcher() const {
240 return embedded_worker_dispatcher_
.get();
243 AudioInputMessageFilter
* audio_input_message_filter() {
244 return audio_input_message_filter_
.get();
247 AudioMessageFilter
* audio_message_filter() {
248 return audio_message_filter_
.get();
251 MidiMessageFilter
* midi_message_filter() {
252 return midi_message_filter_
.get();
255 #if defined(OS_ANDROID)
256 RendererDemuxerAndroid
* renderer_demuxer() {
257 return renderer_demuxer_
.get();
261 // Creates the embedder implementation of WebMediaStreamCenter.
262 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
263 blink::WebMediaStreamCenter
* CreateMediaStreamCenter(
264 blink::WebMediaStreamCenterClient
* client
);
266 // Returns a factory used for creating RTC PeerConnection objects.
267 PeerConnectionDependencyFactory
* GetPeerConnectionDependencyFactory();
269 PeerConnectionTracker
* peer_connection_tracker() {
270 return peer_connection_tracker_
.get();
273 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
274 P2PSocketDispatcher
* p2p_socket_dispatcher() {
275 return p2p_socket_dispatcher_
.get();
278 VideoCaptureImplManager
* video_capture_impl_manager() const {
279 return vc_manager_
.get();
282 GamepadSharedMemoryReader
* gamepad_shared_memory_reader() const {
283 return gamepad_shared_memory_reader_
.get();
286 // Get the GPU channel. Returns NULL if the channel is not established or
288 GpuChannelHost
* GetGpuChannel();
290 // Returns a MessageLoopProxy instance corresponding to the message loop
291 // of the thread on which file operations should be run. Must be called
292 // on the renderer's main thread.
293 scoped_refptr
<base::MessageLoopProxy
> GetFileThreadMessageLoopProxy();
295 // Returns a MessageLoopProxy instance corresponding to the message loop
296 // of the thread on which media operations should be run. Must be called
297 // on the renderer's main thread.
298 scoped_refptr
<base::MessageLoopProxy
> GetMediaThreadMessageLoopProxy();
300 // Causes the idle handler to skip sending idle notifications
301 // on the two next scheduled calls, so idle notifications are
302 // not sent for at least one notification delay.
303 void PostponeIdleNotification();
305 scoped_refptr
<media::GpuVideoAcceleratorFactories
> GetGpuFactories();
307 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
308 SharedMainThreadContextProvider();
310 // AudioRendererMixerManager instance which manages renderer side mixer
311 // instances shared based on configured audio parameters. Lazily created on
313 AudioRendererMixerManager
* GetAudioRendererMixerManager();
315 // AudioHardwareConfig contains audio hardware configuration for
316 // renderer side clients. Creation requires a synchronous IPC call so it is
317 // lazily created on the first call.
318 media::AudioHardwareConfig
* GetAudioHardwareConfig();
321 void PreCacheFontCharacters(const LOGFONT
& log_font
,
322 const base::string16
& str
);
325 #if defined(ENABLE_WEBRTC)
326 WebRTCIdentityService
* get_webrtc_identity_service() {
327 return webrtc_identity_service_
.get();
331 // For producing custom V8 histograms. Custom histograms are produced if all
332 // RenderViews share the same host, and the host is in the pre-specified set
333 // of hosts we want to produce custom diagrams for. The name for a custom
334 // diagram is the name of the corresponding generic diagram plus a
335 // host-specific suffix.
336 class CONTENT_EXPORT HistogramCustomizer
{
338 HistogramCustomizer();
339 ~HistogramCustomizer();
341 // Called when a top frame of a RenderView navigates. This function updates
342 // RenderThreadImpl's information about whether all RenderViews are
343 // displaying a page from the same host. |host| is the host where a
344 // RenderView navigated, and |view_count| is the number of RenderViews in
346 void RenderViewNavigatedToHost(const std::string
& host
, size_t view_count
);
348 // Used for customizing some histograms if all RenderViews share the same
349 // host. Returns the current custom histogram name to use for
350 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
351 std::string
ConvertToCustomHistogramName(const char* histogram_name
) const;
354 friend class RenderThreadImplUnittest
;
356 // Used for updating the information on which is the common host which all
357 // RenderView's share (if any). If there is no common host, this function is
358 // called with an empty string.
359 void SetCommonHost(const std::string
& host
);
361 // The current common host of the RenderViews; empty string if there is no
363 std::string common_host_
;
364 // The corresponding suffix.
365 std::string common_host_histogram_suffix_
;
366 // Set of histograms for which we want to produce a custom histogram if
368 std::set
<std::string
> custom_histograms_
;
370 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer
);
373 HistogramCustomizer
* histogram_customizer() {
374 return &histogram_customizer_
;
377 void SetFlingCurveParameters(const std::vector
<float>& new_touchpad
,
378 const std::vector
<float>& new_touchscreen
);
380 // Retrieve current gamepad data.
381 void SampleGamepads(blink::WebGamepads
* data
);
383 // Set a listener for gamepad connected/disconnected events.
384 // A non-null listener must be set first before calling SampleGamepads.
385 void SetGamepadListener(blink::WebGamepadListener
* listener
);
387 // Called by a RenderWidget when it is created or destroyed. This
388 // allows the process to know when there are no visible widgets.
389 void WidgetCreated();
390 void WidgetDestroyed();
392 void WidgetRestored();
394 void AddEmbeddedWorkerRoute(int32 routing_id
, IPC::Listener
* listener
);
395 void RemoveEmbeddedWorkerRoute(int32 routing_id
);
399 virtual bool OnControlMessageReceived(const IPC::Message
& msg
) OVERRIDE
;
401 // GpuChannelHostFactory implementation:
402 virtual bool IsMainThread() OVERRIDE
;
403 virtual base::MessageLoop
* GetMainLoop() OVERRIDE
;
404 virtual scoped_refptr
<base::MessageLoopProxy
> GetIOLoopProxy() OVERRIDE
;
405 virtual scoped_ptr
<base::SharedMemory
> AllocateSharedMemory(
406 size_t size
) OVERRIDE
;
407 virtual bool CreateViewCommandBuffer(
409 const GPUCreateCommandBufferConfig
& init_params
,
410 int32 route_id
) OVERRIDE
;
411 virtual void CreateImage(
412 gfx::PluginWindowHandle window
,
414 const CreateImageCallback
& callback
) OVERRIDE
;
415 virtual void DeleteImage(int32 image_id
, int32 sync_point
) OVERRIDE
;
416 virtual scoped_ptr
<gfx::GpuMemoryBuffer
> AllocateGpuMemoryBuffer(
419 unsigned internalformat
,
420 unsigned usage
) OVERRIDE
;
422 // mojo::ServiceProvider implementation:
423 virtual void ConnectToService(
424 const mojo::String
& service_url
,
425 const mojo::String
& service_name
,
426 mojo::ScopedMessagePipeHandle message_pipe
,
427 const mojo::String
& requestor_url
) OVERRIDE
;
431 void OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
432 const std::string
& host
,
434 void OnCreateNewView(const ViewMsg_New_Params
& params
);
435 void OnTransferBitmap(const SkBitmap
& bitmap
, int resource_id
);
436 void OnPurgePluginListCache(bool reload_pages
);
437 void OnNetworkTypeChanged(net::NetworkChangeNotifier::ConnectionType type
);
438 void OnGetAccessibilityTree();
439 void OnTempCrashWithData(const GURL
& data
);
440 void OnUpdateTimezone();
441 void OnMemoryPressure(
442 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
443 #if defined(OS_ANDROID)
444 void OnSetWebKitSharedTimersSuspended(bool suspend
);
446 #if defined(OS_MACOSX)
447 void OnUpdateScrollbarTheme(float initial_button_delay
,
448 float autoscroll_button_delay
,
449 bool jump_on_track_click
,
450 blink::ScrollerStyle preferred_scroller_style
,
453 void OnCreateNewSharedWorker(
454 const WorkerProcessMsg_CreateWorker_Params
& params
);
456 void IdleHandlerInForegroundTab();
458 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
> CreateOffscreenContext3d();
460 // These objects live solely on the render thread.
461 scoped_ptr
<AppCacheDispatcher
> appcache_dispatcher_
;
462 scoped_ptr
<DomStorageDispatcher
> dom_storage_dispatcher_
;
463 scoped_ptr
<IndexedDBDispatcher
> main_thread_indexed_db_dispatcher_
;
464 scoped_ptr
<RendererWebKitPlatformSupportImpl
> webkit_platform_support_
;
465 scoped_ptr
<EmbeddedWorkerDispatcher
> embedded_worker_dispatcher_
;
467 // Used on the render thread and deleted by WebKit at shutdown.
468 blink::WebMediaStreamCenter
* media_stream_center_
;
470 // Used on the renderer and IPC threads.
471 scoped_refptr
<DBMessageFilter
> db_message_filter_
;
472 scoped_refptr
<AudioInputMessageFilter
> audio_input_message_filter_
;
473 scoped_refptr
<AudioMessageFilter
> audio_message_filter_
;
474 scoped_refptr
<MidiMessageFilter
> midi_message_filter_
;
475 #if defined(OS_ANDROID)
476 scoped_refptr
<RendererDemuxerAndroid
> renderer_demuxer_
;
478 scoped_refptr
<DevToolsAgentFilter
> devtools_agent_message_filter_
;
480 scoped_ptr
<PeerConnectionDependencyFactory
> peer_connection_factory_
;
482 // This is used to communicate to the browser process the status
483 // of all the peer connections created in the renderer.
484 scoped_ptr
<PeerConnectionTracker
> peer_connection_tracker_
;
486 // Dispatches all P2P sockets.
487 scoped_refptr
<P2PSocketDispatcher
> p2p_socket_dispatcher_
;
489 // Used on the render thread.
490 scoped_ptr
<VideoCaptureImplManager
> vc_manager_
;
492 // The count of RenderWidgets running through this thread.
495 // The count of hidden RenderWidgets running through this thread.
496 int hidden_widget_count_
;
498 // The current value of the idle notification timer delay.
499 int64 idle_notification_delay_in_ms_
;
501 // The number of idle handler calls that skip sending idle notifications.
502 int idle_notifications_to_skip_
;
504 bool suspend_webkit_shared_timer_
;
505 bool notify_webkit_of_modal_loop_
;
506 bool webkit_shared_timer_suspended_
;
508 // The following flag is used to control layout test specific behavior.
509 bool layout_test_mode_
;
511 // Timer that periodically calls IdleHandler.
512 base::RepeatingTimer
<RenderThreadImpl
> idle_timer_
;
514 // The channel from the renderer process to the GPU process.
515 scoped_refptr
<GpuChannelHost
> gpu_channel_
;
517 // Cache of variables that are needed on the compositor thread by
518 // GpuChannelHostFactory methods.
519 scoped_refptr
<base::MessageLoopProxy
> io_message_loop_proxy_
;
521 // A lazily initiated thread on which file operations are run.
522 scoped_ptr
<base::Thread
> file_thread_
;
524 // May be null if overridden by ContentRendererClient.
525 scoped_ptr
<base::Thread
> compositor_thread_
;
527 // Thread for running multimedia operations (e.g., video decoding).
528 scoped_ptr
<base::Thread
> media_thread_
;
530 // Will point to appropriate MessageLoopProxy after initialization,
531 // regardless of whether |compositor_thread_| is overriden.
532 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy_
;
534 // May be null if unused by the |input_handler_manager_|.
535 scoped_refptr
<InputEventFilter
> input_event_filter_
;
536 scoped_ptr
<InputHandlerManager
> input_handler_manager_
;
537 scoped_refptr
<IPC::ForwardingMessageFilter
> compositor_output_surface_filter_
;
539 scoped_refptr
<ContextProviderCommandBuffer
> shared_main_thread_contexts_
;
541 ObserverList
<RenderProcessObserver
> observers_
;
543 scoped_refptr
<ContextProviderCommandBuffer
> gpu_va_context_provider_
;
545 scoped_ptr
<AudioRendererMixerManager
> audio_renderer_mixer_manager_
;
546 scoped_ptr
<media::AudioHardwareConfig
> audio_hardware_config_
;
548 HistogramCustomizer histogram_customizer_
;
550 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
552 scoped_ptr
<WebRTCIdentityService
> webrtc_identity_service_
;
554 scoped_ptr
<GamepadSharedMemoryReader
> gamepad_shared_memory_reader_
;
556 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
557 // multiple threads. Current allocation mechanism for IOSurface
558 // backed GpuMemoryBuffers prevent this. crbug.com/325045
559 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_
;
561 // Compositor settings
562 bool is_gpu_rasterization_enabled_
;
563 bool is_gpu_rasterization_forced_
;
564 bool is_impl_side_painting_enabled_
;
565 bool is_low_res_tiling_enabled_
;
566 bool is_lcd_text_enabled_
;
567 bool is_distance_field_text_enabled_
;
568 bool is_zero_copy_enabled_
;
569 bool is_one_copy_enabled_
;
571 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl
);
574 } // namespace content
576 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_