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/common/gpu/gpu_result_codes.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "net/base/network_change_notifier.h"
25 #include "third_party/WebKit/public/platform/WebConnectionType.h"
26 #include "ui/gfx/native_widget_types.h"
28 #if defined(OS_MACOSX)
29 #include "third_party/WebKit/public/web/mac/WebScrollbarTheme.h"
34 struct ViewMsg_New_Params
;
35 struct WorkerProcessMsg_CreateWorker_Params
;
39 class WebGamepadListener
;
40 class WebGraphicsContext3D
;
41 class WebMediaStreamCenter
;
42 class WebMediaStreamCenterClient
;
46 class MessageLoopProxy
;
51 class ContextProvider
;
55 class ForwardingMessageFilter
;
60 class AudioHardwareConfig
;
61 class GpuVideoAcceleratorFactories
;
70 class ContextProviderWebContext
;
71 class GrContextForWebGraphicsContext3D
;
77 class AppCacheDispatcher
;
78 class AecDumpMessageFilter
;
79 class AudioInputMessageFilter
;
80 class AudioMessageFilter
;
81 class AudioRendererMixerManager
;
82 class ContextProviderCommandBuffer
;
83 class DBMessageFilter
;
84 class DevToolsAgentFilter
;
85 class DomStorageDispatcher
;
86 class EmbeddedWorkerDispatcher
;
87 class GamepadSharedMemoryReader
;
89 class IndexedDBDispatcher
;
90 class InputEventFilter
;
91 class InputHandlerManager
;
92 class MediaStreamCenter
;
94 class PeerConnectionDependencyFactory
;
95 class MidiMessageFilter
;
96 class NetInfoDispatcher
;
97 class P2PSocketDispatcher
;
98 class PeerConnectionTracker
;
99 class RendererDemuxerAndroid
;
100 class RendererWebKitPlatformSupportImpl
;
101 class RenderProcessObserver
;
102 class VideoCaptureImplManager
;
103 class WebGraphicsContext3DCommandBufferImpl
;
104 class WebRTCIdentityService
;
106 // The RenderThreadImpl class represents a background thread where RenderView
107 // instances live. The RenderThread supports an API that is used by its
108 // consumer to talk indirectly to the RenderViews and supporting objects.
109 // Likewise, it provides an API for the RenderViews to talk back to the main
110 // process (i.e., their corresponding WebContentsImpl).
112 // Most of the communication occurs in the form of IPC messages. They are
113 // routed to the RenderThread according to the routing IDs of the messages.
114 // The routing IDs correspond to RenderView instances.
115 class CONTENT_EXPORT RenderThreadImpl
: public RenderThread
,
117 public GpuChannelHostFactory
{
119 static RenderThreadImpl
* current();
122 // Constructor that's used when running in single process mode.
123 explicit RenderThreadImpl(const std::string
& channel_name
);
124 virtual ~RenderThreadImpl();
125 virtual void Shutdown() OVERRIDE
;
127 // When initializing WebKit, ensure that any schemes needed for the content
128 // module are registered properly. Static to allow sharing with tests.
129 static void RegisterSchemes();
131 // Notify V8 that the date/time configuration of the system might have
133 static void NotifyTimezoneChange();
135 // RenderThread implementation:
136 virtual bool Send(IPC::Message
* msg
) OVERRIDE
;
137 virtual base::MessageLoop
* GetMessageLoop() OVERRIDE
;
138 virtual IPC::SyncChannel
* GetChannel() OVERRIDE
;
139 virtual std::string
GetLocale() OVERRIDE
;
140 virtual IPC::SyncMessageFilter
* GetSyncMessageFilter() OVERRIDE
;
141 virtual scoped_refptr
<base::MessageLoopProxy
> GetIOMessageLoopProxy()
143 virtual void AddRoute(int32 routing_id
, IPC::Listener
* listener
) OVERRIDE
;
144 virtual void RemoveRoute(int32 routing_id
) OVERRIDE
;
145 virtual int GenerateRoutingID() OVERRIDE
;
146 virtual void AddFilter(IPC::MessageFilter
* filter
) OVERRIDE
;
147 virtual void RemoveFilter(IPC::MessageFilter
* filter
) OVERRIDE
;
148 virtual void AddObserver(RenderProcessObserver
* observer
) OVERRIDE
;
149 virtual void RemoveObserver(RenderProcessObserver
* observer
) OVERRIDE
;
150 virtual void SetResourceDispatcherDelegate(
151 ResourceDispatcherDelegate
* delegate
) OVERRIDE
;
152 virtual void EnsureWebKitInitialized() OVERRIDE
;
153 virtual void RecordAction(const base::UserMetricsAction
& action
) OVERRIDE
;
154 virtual void RecordComputedAction(const std::string
& action
) OVERRIDE
;
155 virtual scoped_ptr
<base::SharedMemory
> HostAllocateSharedMemoryBuffer(
156 size_t buffer_size
) OVERRIDE
;
157 virtual void RegisterExtension(v8::Extension
* extension
) OVERRIDE
;
158 virtual void ScheduleIdleHandler(int64 initial_delay_ms
) OVERRIDE
;
159 virtual void IdleHandler() OVERRIDE
;
160 virtual int64
GetIdleNotificationDelayInMs() const OVERRIDE
;
161 virtual void SetIdleNotificationDelayInMs(
162 int64 idle_notification_delay_in_ms
) OVERRIDE
;
163 virtual void UpdateHistograms(int sequence_number
) OVERRIDE
;
164 virtual int PostTaskToAllWebWorkers(const base::Closure
& closure
) OVERRIDE
;
165 virtual bool ResolveProxy(const GURL
& url
, std::string
* proxy_list
) OVERRIDE
;
166 virtual base::WaitableEvent
* GetShutdownEvent() OVERRIDE
;
168 virtual void PreCacheFont(const LOGFONT
& log_font
) OVERRIDE
;
169 virtual void ReleaseCachedFonts() OVERRIDE
;
171 virtual ServiceRegistry
* GetServiceRegistry() OVERRIDE
;
173 // Synchronously establish a channel to the GPU plugin if not previously
174 // established or if it has been lost (for example if the GPU plugin crashed).
175 // If there is a pending asynchronous request, it will be completed by the
176 // time this routine returns.
177 GpuChannelHost
* EstablishGpuChannelSync(CauseForGpuLaunch
);
180 // These methods modify how the next message is sent. Normally, when sending
181 // a synchronous message that runs a nested message loop, we need to suspend
182 // callbacks into WebKit. This involves disabling timers and deferring
183 // resource loads. However, there are exceptions when we need to customize
185 void DoNotSuspendWebKitSharedTimer();
186 void DoNotNotifyWebKitOfModalLoop();
188 // True if we are running layout tests. This currently disables forwarding
189 // various status messages to the console, skips network error pages, and
190 // short circuits size update and focus events.
191 bool layout_test_mode() const {
192 return layout_test_mode_
;
194 void set_layout_test_mode(bool layout_test_mode
) {
195 layout_test_mode_
= layout_test_mode
;
198 RendererWebKitPlatformSupportImpl
* webkit_platform_support() const {
199 DCHECK(webkit_platform_support_
);
200 return webkit_platform_support_
.get();
203 IPC::ForwardingMessageFilter
* compositor_output_surface_filter() const {
204 return compositor_output_surface_filter_
.get();
207 InputHandlerManager
* input_handler_manager() const {
208 return input_handler_manager_
.get();
211 // Will be NULL if threaded compositing has not been enabled.
212 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy() const {
213 return compositor_message_loop_proxy_
;
216 bool is_gpu_rasterization_enabled() const {
217 return is_gpu_rasterization_enabled_
;
220 bool is_gpu_rasterization_forced() const {
221 return is_gpu_rasterization_forced_
;
224 bool is_impl_side_painting_enabled() const {
225 return is_impl_side_painting_enabled_
;
228 bool is_low_res_tiling_enabled() const { return is_low_res_tiling_enabled_
; }
230 bool is_lcd_text_enabled() const { return is_lcd_text_enabled_
; }
232 bool is_distance_field_text_enabled() const {
233 return is_distance_field_text_enabled_
;
236 bool is_zero_copy_enabled() const { return is_zero_copy_enabled_
; }
238 bool is_one_copy_enabled() const { return is_one_copy_enabled_
; }
240 AppCacheDispatcher
* appcache_dispatcher() const {
241 return appcache_dispatcher_
.get();
244 DomStorageDispatcher
* dom_storage_dispatcher() const {
245 return dom_storage_dispatcher_
.get();
248 EmbeddedWorkerDispatcher
* embedded_worker_dispatcher() const {
249 return embedded_worker_dispatcher_
.get();
252 AudioInputMessageFilter
* audio_input_message_filter() {
253 return audio_input_message_filter_
.get();
256 AudioMessageFilter
* audio_message_filter() {
257 return audio_message_filter_
.get();
260 MidiMessageFilter
* midi_message_filter() {
261 return midi_message_filter_
.get();
264 #if defined(OS_ANDROID)
265 RendererDemuxerAndroid
* renderer_demuxer() {
266 return renderer_demuxer_
.get();
270 // Creates the embedder implementation of WebMediaStreamCenter.
271 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
272 blink::WebMediaStreamCenter
* CreateMediaStreamCenter(
273 blink::WebMediaStreamCenterClient
* client
);
275 // Returns a factory used for creating RTC PeerConnection objects.
276 PeerConnectionDependencyFactory
* GetPeerConnectionDependencyFactory();
278 PeerConnectionTracker
* peer_connection_tracker() {
279 return peer_connection_tracker_
.get();
282 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
283 P2PSocketDispatcher
* p2p_socket_dispatcher() {
284 return p2p_socket_dispatcher_
.get();
287 VideoCaptureImplManager
* video_capture_impl_manager() const {
288 return vc_manager_
.get();
291 GamepadSharedMemoryReader
* gamepad_shared_memory_reader() const {
292 return gamepad_shared_memory_reader_
.get();
295 // Get the GPU channel. Returns NULL if the channel is not established or
297 GpuChannelHost
* GetGpuChannel();
299 // Returns a MessageLoopProxy instance corresponding to the message loop
300 // of the thread on which file operations should be run. Must be called
301 // on the renderer's main thread.
302 scoped_refptr
<base::MessageLoopProxy
> GetFileThreadMessageLoopProxy();
304 // Returns a MessageLoopProxy instance corresponding to the message loop
305 // of the thread on which media operations should be run. Must be called
306 // on the renderer's main thread.
307 scoped_refptr
<base::MessageLoopProxy
> GetMediaThreadMessageLoopProxy();
309 // Causes the idle handler to skip sending idle notifications
310 // on the two next scheduled calls, so idle notifications are
311 // not sent for at least one notification delay.
312 void PostponeIdleNotification();
314 scoped_refptr
<media::GpuVideoAcceleratorFactories
> GetGpuFactories();
316 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
317 SharedMainThreadContextProvider();
319 // AudioRendererMixerManager instance which manages renderer side mixer
320 // instances shared based on configured audio parameters. Lazily created on
322 AudioRendererMixerManager
* GetAudioRendererMixerManager();
324 // AudioHardwareConfig contains audio hardware configuration for
325 // renderer side clients. Creation requires a synchronous IPC call so it is
326 // lazily created on the first call.
327 media::AudioHardwareConfig
* GetAudioHardwareConfig();
330 void PreCacheFontCharacters(const LOGFONT
& log_font
,
331 const base::string16
& str
);
334 #if defined(ENABLE_WEBRTC)
335 WebRTCIdentityService
* get_webrtc_identity_service() {
336 return webrtc_identity_service_
.get();
340 // For producing custom V8 histograms. Custom histograms are produced if all
341 // RenderViews share the same host, and the host is in the pre-specified set
342 // of hosts we want to produce custom diagrams for. The name for a custom
343 // diagram is the name of the corresponding generic diagram plus a
344 // host-specific suffix.
345 class CONTENT_EXPORT HistogramCustomizer
{
347 HistogramCustomizer();
348 ~HistogramCustomizer();
350 // Called when a top frame of a RenderView navigates. This function updates
351 // RenderThreadImpl's information about whether all RenderViews are
352 // displaying a page from the same host. |host| is the host where a
353 // RenderView navigated, and |view_count| is the number of RenderViews in
355 void RenderViewNavigatedToHost(const std::string
& host
, size_t view_count
);
357 // Used for customizing some histograms if all RenderViews share the same
358 // host. Returns the current custom histogram name to use for
359 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
360 std::string
ConvertToCustomHistogramName(const char* histogram_name
) const;
363 friend class RenderThreadImplUnittest
;
365 // Used for updating the information on which is the common host which all
366 // RenderView's share (if any). If there is no common host, this function is
367 // called with an empty string.
368 void SetCommonHost(const std::string
& host
);
370 // The current common host of the RenderViews; empty string if there is no
372 std::string common_host_
;
373 // The corresponding suffix.
374 std::string common_host_histogram_suffix_
;
375 // Set of histograms for which we want to produce a custom histogram if
377 std::set
<std::string
> custom_histograms_
;
379 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer
);
382 HistogramCustomizer
* histogram_customizer() {
383 return &histogram_customizer_
;
386 void SetFlingCurveParameters(const std::vector
<float>& new_touchpad
,
387 const std::vector
<float>& new_touchscreen
);
389 // Retrieve current gamepad data.
390 void SampleGamepads(blink::WebGamepads
* data
);
392 // Set a listener for gamepad connected/disconnected events.
393 // A non-null listener must be set first before calling SampleGamepads.
394 void SetGamepadListener(blink::WebGamepadListener
* listener
);
396 // Called by a RenderWidget when it is created or destroyed. This
397 // allows the process to know when there are no visible widgets.
398 void WidgetCreated();
399 void WidgetDestroyed();
401 void WidgetRestored();
403 void AddEmbeddedWorkerRoute(int32 routing_id
, IPC::Listener
* listener
);
404 void RemoveEmbeddedWorkerRoute(int32 routing_id
);
406 void RegisterPendingRenderFrameConnect(int routing_id
,
407 mojo::ScopedMessagePipeHandle handle
);
411 virtual bool OnControlMessageReceived(const IPC::Message
& msg
) OVERRIDE
;
413 // GpuChannelHostFactory implementation:
414 virtual bool IsMainThread() OVERRIDE
;
415 virtual base::MessageLoop
* GetMainLoop() OVERRIDE
;
416 virtual scoped_refptr
<base::MessageLoopProxy
> GetIOLoopProxy() OVERRIDE
;
417 virtual scoped_ptr
<base::SharedMemory
> AllocateSharedMemory(
418 size_t size
) OVERRIDE
;
419 virtual CreateCommandBufferResult
CreateViewCommandBuffer(
421 const GPUCreateCommandBufferConfig
& init_params
,
422 int32 route_id
) OVERRIDE
;
423 virtual scoped_ptr
<gfx::GpuMemoryBuffer
> AllocateGpuMemoryBuffer(
426 unsigned internalformat
,
427 unsigned usage
) OVERRIDE
;
428 virtual void DeleteGpuMemoryBuffer(
429 scoped_ptr
<gfx::GpuMemoryBuffer
> buffer
) OVERRIDE
;
433 void OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
434 const std::string
& host
,
436 void OnCreateNewView(const ViewMsg_New_Params
& params
);
437 void OnTransferBitmap(const SkBitmap
& bitmap
, int resource_id
);
438 void OnPurgePluginListCache(bool reload_pages
);
439 void OnNetworkTypeChanged(net::NetworkChangeNotifier::ConnectionType type
);
440 void OnGetAccessibilityTree();
441 void OnTempCrashWithData(const GURL
& data
);
442 void OnUpdateTimezone();
443 void OnMemoryPressure(
444 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
445 #if defined(OS_ANDROID)
446 void OnSetWebKitSharedTimersSuspended(bool suspend
);
448 #if defined(OS_MACOSX)
449 void OnUpdateScrollbarTheme(float initial_button_delay
,
450 float autoscroll_button_delay
,
451 bool jump_on_track_click
,
452 blink::ScrollerStyle preferred_scroller_style
,
455 void OnCreateNewSharedWorker(
456 const WorkerProcessMsg_CreateWorker_Params
& params
);
458 void IdleHandlerInForegroundTab();
460 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
> CreateOffscreenContext3d();
462 // These objects live solely on the render thread.
463 scoped_ptr
<AppCacheDispatcher
> appcache_dispatcher_
;
464 scoped_ptr
<DomStorageDispatcher
> dom_storage_dispatcher_
;
465 scoped_ptr
<IndexedDBDispatcher
> main_thread_indexed_db_dispatcher_
;
466 scoped_ptr
<RendererWebKitPlatformSupportImpl
> webkit_platform_support_
;
467 scoped_ptr
<EmbeddedWorkerDispatcher
> embedded_worker_dispatcher_
;
469 // Used on the render thread and deleted by WebKit at shutdown.
470 blink::WebMediaStreamCenter
* media_stream_center_
;
472 // Used on the renderer and IPC threads.
473 scoped_refptr
<DBMessageFilter
> db_message_filter_
;
474 scoped_refptr
<AudioInputMessageFilter
> audio_input_message_filter_
;
475 scoped_refptr
<AudioMessageFilter
> audio_message_filter_
;
476 scoped_refptr
<MidiMessageFilter
> midi_message_filter_
;
477 #if defined(OS_ANDROID)
478 scoped_refptr
<RendererDemuxerAndroid
> renderer_demuxer_
;
480 scoped_refptr
<DevToolsAgentFilter
> devtools_agent_message_filter_
;
482 scoped_ptr
<PeerConnectionDependencyFactory
> peer_connection_factory_
;
484 // This is used to communicate to the browser process the status
485 // of all the peer connections created in the renderer.
486 scoped_ptr
<PeerConnectionTracker
> peer_connection_tracker_
;
488 // Dispatches all P2P sockets.
489 scoped_refptr
<P2PSocketDispatcher
> p2p_socket_dispatcher_
;
491 // Used on the render thread.
492 scoped_ptr
<VideoCaptureImplManager
> vc_manager_
;
494 // Used for communicating registering AEC dump consumers with the browser and
495 // receving AEC dump file handles when AEC dump is enabled. An AEC dump is
496 // diagnostic audio data for WebRTC stored locally when enabled by the user in
497 // chrome://webrtc-internals.
498 scoped_refptr
<AecDumpMessageFilter
> aec_dump_message_filter_
;
500 // The count of RenderWidgets running through this thread.
503 // The count of hidden RenderWidgets running through this thread.
504 int hidden_widget_count_
;
506 // The current value of the idle notification timer delay.
507 int64 idle_notification_delay_in_ms_
;
509 // The number of idle handler calls that skip sending idle notifications.
510 int idle_notifications_to_skip_
;
512 bool suspend_webkit_shared_timer_
;
513 bool notify_webkit_of_modal_loop_
;
514 bool webkit_shared_timer_suspended_
;
516 // The following flag is used to control layout test specific behavior.
517 bool layout_test_mode_
;
519 // Timer that periodically calls IdleHandler.
520 base::RepeatingTimer
<RenderThreadImpl
> idle_timer_
;
522 // The channel from the renderer process to the GPU process.
523 scoped_refptr
<GpuChannelHost
> gpu_channel_
;
525 // Cache of variables that are needed on the compositor thread by
526 // GpuChannelHostFactory methods.
527 scoped_refptr
<base::MessageLoopProxy
> io_message_loop_proxy_
;
529 // A lazily initiated thread on which file operations are run.
530 scoped_ptr
<base::Thread
> file_thread_
;
532 // May be null if overridden by ContentRendererClient.
533 scoped_ptr
<base::Thread
> compositor_thread_
;
535 // Thread for running multimedia operations (e.g., video decoding).
536 scoped_ptr
<base::Thread
> media_thread_
;
538 // Will point to appropriate MessageLoopProxy after initialization,
539 // regardless of whether |compositor_thread_| is overriden.
540 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy_
;
542 // May be null if unused by the |input_handler_manager_|.
543 scoped_refptr
<InputEventFilter
> input_event_filter_
;
544 scoped_ptr
<InputHandlerManager
> input_handler_manager_
;
545 scoped_refptr
<IPC::ForwardingMessageFilter
> compositor_output_surface_filter_
;
547 scoped_refptr
<ContextProviderCommandBuffer
> shared_main_thread_contexts_
;
549 ObserverList
<RenderProcessObserver
> observers_
;
551 scoped_refptr
<ContextProviderCommandBuffer
> gpu_va_context_provider_
;
553 scoped_ptr
<AudioRendererMixerManager
> audio_renderer_mixer_manager_
;
554 scoped_ptr
<media::AudioHardwareConfig
> audio_hardware_config_
;
556 HistogramCustomizer histogram_customizer_
;
558 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
560 scoped_ptr
<WebRTCIdentityService
> webrtc_identity_service_
;
562 scoped_ptr
<GamepadSharedMemoryReader
> gamepad_shared_memory_reader_
;
564 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
565 // multiple threads. Current allocation mechanism for IOSurface
566 // backed GpuMemoryBuffers prevent this. crbug.com/325045
567 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_
;
569 scoped_ptr
<MemoryObserver
> memory_observer_
;
571 // Compositor settings
572 bool is_gpu_rasterization_enabled_
;
573 bool is_gpu_rasterization_forced_
;
574 bool is_impl_side_painting_enabled_
;
575 bool is_low_res_tiling_enabled_
;
576 bool is_lcd_text_enabled_
;
577 bool is_distance_field_text_enabled_
;
578 bool is_zero_copy_enabled_
;
579 bool is_one_copy_enabled_
;
581 std::map
<int, mojo::MessagePipeHandle
> pending_render_frame_connects_
;
583 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl
);
586 } // namespace content
588 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_