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 WebGraphicsContext3D
;
40 class WebMediaStreamCenter
;
41 class WebMediaStreamCenterClient
;
45 class MessageLoopProxy
;
46 class SingleThreadTaskRunner
;
51 class ContextProvider
;
59 class AudioHardwareConfig
;
60 class GpuVideoAcceleratorFactories
;
69 class ContextProviderWebContext
;
70 class GrContextForWebGraphicsContext3D
;
76 class AppCacheDispatcher
;
77 class AecDumpMessageFilter
;
78 class AudioInputMessageFilter
;
79 class AudioMessageFilter
;
80 class AudioRendererMixerManager
;
81 class CompositorForwardingMessageFilter
;
82 class ContextProviderCommandBuffer
;
83 class DBMessageFilter
;
84 class DevToolsAgentFilter
;
85 class DomStorageDispatcher
;
86 class EmbeddedWorkerDispatcher
;
88 class IndexedDBDispatcher
;
89 class InputEventFilter
;
90 class InputHandlerManager
;
91 class MediaStreamCenter
;
93 class PeerConnectionDependencyFactory
;
94 class MidiMessageFilter
;
95 class NetInfoDispatcher
;
96 class P2PSocketDispatcher
;
97 class PeerConnectionTracker
;
98 class RenderProcessObserver
;
99 class RendererBlinkPlatformImpl
;
100 class RendererDemuxerAndroid
;
101 class RendererScheduler
;
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 // Constructor that's used in RendererMain.
125 explicit RenderThreadImpl(scoped_ptr
<base::MessageLoop
> main_message_loop
);
126 ~RenderThreadImpl() override
;
127 void Shutdown() override
;
129 // When initializing WebKit, ensure that any schemes needed for the content
130 // module are registered properly. Static to allow sharing with tests.
131 static void RegisterSchemes();
133 // Notify V8 that the date/time configuration of the system might have
135 static void NotifyTimezoneChange();
137 // RenderThread implementation:
138 bool Send(IPC::Message
* msg
) override
;
139 base::MessageLoop
* GetMessageLoop() override
;
140 IPC::SyncChannel
* GetChannel() override
;
141 std::string
GetLocale() override
;
142 IPC::SyncMessageFilter
* GetSyncMessageFilter() override
;
143 scoped_refptr
<base::MessageLoopProxy
> GetIOMessageLoopProxy() override
;
144 void AddRoute(int32 routing_id
, IPC::Listener
* listener
) override
;
145 void RemoveRoute(int32 routing_id
) override
;
146 int GenerateRoutingID() override
;
147 void AddFilter(IPC::MessageFilter
* filter
) override
;
148 void RemoveFilter(IPC::MessageFilter
* filter
) override
;
149 void AddObserver(RenderProcessObserver
* observer
) override
;
150 void RemoveObserver(RenderProcessObserver
* observer
) override
;
151 void SetResourceDispatcherDelegate(
152 ResourceDispatcherDelegate
* delegate
) override
;
153 void EnsureWebKitInitialized() override
;
154 void RecordAction(const base::UserMetricsAction
& action
) override
;
155 void RecordComputedAction(const std::string
& action
) override
;
156 scoped_ptr
<base::SharedMemory
> HostAllocateSharedMemoryBuffer(
157 size_t buffer_size
) override
;
158 void RegisterExtension(v8::Extension
* extension
) override
;
159 void ScheduleIdleHandler(int64 initial_delay_ms
) override
;
160 void IdleHandler() override
;
161 int64
GetIdleNotificationDelayInMs() const override
;
162 void SetIdleNotificationDelayInMs(
163 int64 idle_notification_delay_in_ms
) override
;
164 void UpdateHistograms(int sequence_number
) override
;
165 int PostTaskToAllWebWorkers(const base::Closure
& closure
) override
;
166 bool ResolveProxy(const GURL
& url
, std::string
* proxy_list
) override
;
167 base::WaitableEvent
* GetShutdownEvent() override
;
169 virtual void PreCacheFont(const LOGFONT
& log_font
) override
;
170 virtual void ReleaseCachedFonts() override
;
172 ServiceRegistry
* GetServiceRegistry() override
;
174 // Synchronously establish a channel to the GPU plugin if not previously
175 // established or if it has been lost (for example if the GPU plugin crashed).
176 // If there is a pending asynchronous request, it will be completed by the
177 // time this routine returns.
178 GpuChannelHost
* EstablishGpuChannelSync(CauseForGpuLaunch
);
181 // These methods modify how the next message is sent. Normally, when sending
182 // a synchronous message that runs a nested message loop, we need to suspend
183 // callbacks into WebKit. This involves disabling timers and deferring
184 // resource loads. However, there are exceptions when we need to customize
186 void DoNotSuspendWebKitSharedTimer();
187 void DoNotNotifyWebKitOfModalLoop();
189 // True if we are running layout tests. This currently disables forwarding
190 // various status messages to the console, skips network error pages, and
191 // short circuits size update and focus events.
192 bool layout_test_mode() const {
193 return layout_test_mode_
;
195 void set_layout_test_mode(bool layout_test_mode
) {
196 layout_test_mode_
= layout_test_mode
;
199 RendererScheduler
* renderer_scheduler() const {
200 DCHECK(renderer_scheduler_
);
201 return renderer_scheduler_
.get();
204 RendererBlinkPlatformImpl
* blink_platform_impl() const {
205 DCHECK(blink_platform_impl_
);
206 return blink_platform_impl_
.get();
209 scoped_refptr
<base::SingleThreadTaskRunner
>
210 main_thread_compositor_task_runner() const {
211 return main_thread_compositor_task_runner_
;
214 CompositorForwardingMessageFilter
* compositor_message_filter() const {
215 return compositor_message_filter_
.get();
218 InputHandlerManager
* input_handler_manager() const {
219 return input_handler_manager_
.get();
222 // Will be NULL if threaded compositing has not been enabled.
223 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy() const {
224 return compositor_message_loop_proxy_
;
227 bool is_gpu_rasterization_enabled() const {
228 return is_gpu_rasterization_enabled_
;
231 bool is_gpu_rasterization_forced() const {
232 return is_gpu_rasterization_forced_
;
235 bool is_impl_side_painting_enabled() const {
236 return is_impl_side_painting_enabled_
;
239 bool is_lcd_text_enabled() const { return is_lcd_text_enabled_
; }
241 bool is_distance_field_text_enabled() const {
242 return is_distance_field_text_enabled_
;
245 bool is_zero_copy_enabled() const { return is_zero_copy_enabled_
; }
247 bool is_one_copy_enabled() const { return is_one_copy_enabled_
; }
249 bool use_image_external() const { return use_image_external_
; }
251 AppCacheDispatcher
* appcache_dispatcher() const {
252 return appcache_dispatcher_
.get();
255 DomStorageDispatcher
* dom_storage_dispatcher() const {
256 return dom_storage_dispatcher_
.get();
259 EmbeddedWorkerDispatcher
* embedded_worker_dispatcher() const {
260 return embedded_worker_dispatcher_
.get();
263 AudioInputMessageFilter
* audio_input_message_filter() {
264 return audio_input_message_filter_
.get();
267 AudioMessageFilter
* audio_message_filter() {
268 return audio_message_filter_
.get();
271 MidiMessageFilter
* midi_message_filter() {
272 return midi_message_filter_
.get();
275 #if defined(OS_ANDROID)
276 RendererDemuxerAndroid
* renderer_demuxer() {
277 return renderer_demuxer_
.get();
281 // Creates the embedder implementation of WebMediaStreamCenter.
282 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
283 blink::WebMediaStreamCenter
* CreateMediaStreamCenter(
284 blink::WebMediaStreamCenterClient
* client
);
286 #if defined(ENABLE_WEBRTC)
287 // Returns a factory used for creating RTC PeerConnection objects.
288 PeerConnectionDependencyFactory
* GetPeerConnectionDependencyFactory();
290 PeerConnectionTracker
* peer_connection_tracker() {
291 return peer_connection_tracker_
.get();
294 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
295 P2PSocketDispatcher
* p2p_socket_dispatcher() {
296 return p2p_socket_dispatcher_
.get();
300 VideoCaptureImplManager
* video_capture_impl_manager() const {
301 return vc_manager_
.get();
304 // Get the GPU channel. Returns NULL if the channel is not established or
306 GpuChannelHost
* GetGpuChannel();
308 // Returns a MessageLoopProxy instance corresponding to the message loop
309 // of the thread on which file operations should be run. Must be called
310 // on the renderer's main thread.
311 scoped_refptr
<base::MessageLoopProxy
> GetFileThreadMessageLoopProxy();
313 // Returns a SingleThreadTaskRunner instance corresponding to the message loop
314 // of the thread on which media operations should be run. Must be called
315 // on the renderer's main thread.
316 scoped_refptr
<base::SingleThreadTaskRunner
> GetMediaThreadTaskRunner();
318 // Causes the idle handler to skip sending idle notifications
319 // on the two next scheduled calls, so idle notifications are
320 // not sent for at least one notification delay.
321 void PostponeIdleNotification();
323 scoped_refptr
<media::GpuVideoAcceleratorFactories
> GetGpuFactories();
325 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
326 SharedMainThreadContextProvider();
328 // AudioRendererMixerManager instance which manages renderer side mixer
329 // instances shared based on configured audio parameters. Lazily created on
331 AudioRendererMixerManager
* GetAudioRendererMixerManager();
333 // AudioHardwareConfig contains audio hardware configuration for
334 // renderer side clients. Creation requires a synchronous IPC call so it is
335 // lazily created on the first call.
336 media::AudioHardwareConfig
* GetAudioHardwareConfig();
339 void PreCacheFontCharacters(const LOGFONT
& log_font
,
340 const base::string16
& str
);
343 #if defined(ENABLE_WEBRTC)
344 WebRTCIdentityService
* get_webrtc_identity_service() {
345 return webrtc_identity_service_
.get();
349 // For producing custom V8 histograms. Custom histograms are produced if all
350 // RenderViews share the same host, and the host is in the pre-specified set
351 // of hosts we want to produce custom diagrams for. The name for a custom
352 // diagram is the name of the corresponding generic diagram plus a
353 // host-specific suffix.
354 class CONTENT_EXPORT HistogramCustomizer
{
356 HistogramCustomizer();
357 ~HistogramCustomizer();
359 // Called when a top frame of a RenderView navigates. This function updates
360 // RenderThreadImpl's information about whether all RenderViews are
361 // displaying a page from the same host. |host| is the host where a
362 // RenderView navigated, and |view_count| is the number of RenderViews in
364 void RenderViewNavigatedToHost(const std::string
& host
, size_t view_count
);
366 // Used for customizing some histograms if all RenderViews share the same
367 // host. Returns the current custom histogram name to use for
368 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
369 std::string
ConvertToCustomHistogramName(const char* histogram_name
) const;
372 friend class RenderThreadImplUnittest
;
374 // Used for updating the information on which is the common host which all
375 // RenderView's share (if any). If there is no common host, this function is
376 // called with an empty string.
377 void SetCommonHost(const std::string
& host
);
379 // The current common host of the RenderViews; empty string if there is no
381 std::string common_host_
;
382 // The corresponding suffix.
383 std::string common_host_histogram_suffix_
;
384 // Set of histograms for which we want to produce a custom histogram if
386 std::set
<std::string
> custom_histograms_
;
388 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer
);
391 HistogramCustomizer
* histogram_customizer() {
392 return &histogram_customizer_
;
395 // Retrieve current gamepad data.
396 void SampleGamepads(blink::WebGamepads
* data
);
398 // Called by a RenderWidget when it is created or destroyed. This
399 // allows the process to know when there are no visible widgets.
400 void WidgetCreated();
401 void WidgetDestroyed();
403 void WidgetRestored();
405 void AddEmbeddedWorkerRoute(int32 routing_id
, IPC::Listener
* listener
);
406 void RemoveEmbeddedWorkerRoute(int32 routing_id
);
408 void RegisterPendingRenderFrameConnect(int routing_id
,
409 mojo::ScopedMessagePipeHandle handle
);
413 bool OnControlMessageReceived(const IPC::Message
& msg
) override
;
415 // GpuChannelHostFactory implementation:
416 bool IsMainThread() override
;
417 base::MessageLoop
* GetMainLoop() override
;
418 scoped_refptr
<base::MessageLoopProxy
> GetIOLoopProxy() override
;
419 scoped_ptr
<base::SharedMemory
> AllocateSharedMemory(size_t size
) override
;
420 CreateCommandBufferResult
CreateViewCommandBuffer(
422 const GPUCreateCommandBufferConfig
& init_params
,
423 int32 route_id
) override
;
427 void OnCreateNewFrame(int routing_id
,
428 int parent_routing_id
,
429 int proxy_routing_id
);
430 void OnCreateNewFrameProxy(int routing_id
,
431 int parent_routing_id
,
432 int render_view_routing_id
);
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 #if defined(ENABLE_PLUGINS)
439 void OnPurgePluginListCache(bool reload_pages
);
441 void OnNetworkTypeChanged(net::NetworkChangeNotifier::ConnectionType type
);
442 void OnGetAccessibilityTree();
443 void OnTempCrashWithData(const GURL
& data
);
444 void OnUpdateTimezone();
445 void OnMemoryPressure(
446 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
447 #if defined(OS_ANDROID)
448 void OnSetWebKitSharedTimersSuspended(bool suspend
);
450 #if defined(OS_MACOSX)
451 void OnUpdateScrollbarTheme(float initial_button_delay
,
452 float autoscroll_button_delay
,
453 bool jump_on_track_click
,
454 blink::ScrollerStyle preferred_scroller_style
,
457 void OnCreateNewSharedWorker(
458 const WorkerProcessMsg_CreateWorker_Params
& params
);
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
<RendererScheduler
> renderer_scheduler_
;
467 scoped_ptr
<RendererBlinkPlatformImpl
> blink_platform_impl_
;
468 scoped_ptr
<EmbeddedWorkerDispatcher
> embedded_worker_dispatcher_
;
470 // Used on the render thread and deleted by WebKit at shutdown.
471 blink::WebMediaStreamCenter
* media_stream_center_
;
473 // Used on the renderer and IPC threads.
474 scoped_refptr
<DBMessageFilter
> db_message_filter_
;
475 scoped_refptr
<AudioInputMessageFilter
> audio_input_message_filter_
;
476 scoped_refptr
<AudioMessageFilter
> audio_message_filter_
;
477 scoped_refptr
<MidiMessageFilter
> midi_message_filter_
;
478 #if defined(OS_ANDROID)
479 scoped_refptr
<RendererDemuxerAndroid
> renderer_demuxer_
;
481 scoped_refptr
<DevToolsAgentFilter
> devtools_agent_message_filter_
;
483 #if defined(ENABLE_WEBRTC)
484 scoped_ptr
<PeerConnectionDependencyFactory
> peer_connection_factory_
;
486 // This is used to communicate to the browser process the status
487 // of all the peer connections created in the renderer.
488 scoped_ptr
<PeerConnectionTracker
> peer_connection_tracker_
;
490 // Dispatches all P2P sockets.
491 scoped_refptr
<P2PSocketDispatcher
> p2p_socket_dispatcher_
;
494 // Used on the render thread.
495 scoped_ptr
<VideoCaptureImplManager
> vc_manager_
;
497 // Used for communicating registering AEC dump consumers with the browser and
498 // receving AEC dump file handles when AEC dump is enabled. An AEC dump is
499 // diagnostic audio data for WebRTC stored locally when enabled by the user in
500 // chrome://webrtc-internals.
501 scoped_refptr
<AecDumpMessageFilter
> aec_dump_message_filter_
;
503 // The count of RenderWidgets running through this thread.
506 // The count of hidden RenderWidgets running through this thread.
507 int hidden_widget_count_
;
509 // The current value of the idle notification timer delay.
510 int64 idle_notification_delay_in_ms_
;
512 // The number of idle handler calls that skip sending idle notifications.
513 int idle_notifications_to_skip_
;
515 bool suspend_webkit_shared_timer_
;
516 bool notify_webkit_of_modal_loop_
;
517 bool webkit_shared_timer_suspended_
;
519 // The following flag is used to control layout test specific behavior.
520 bool layout_test_mode_
;
522 // Timer that periodically calls IdleHandler.
523 base::RepeatingTimer
<RenderThreadImpl
> idle_timer_
;
525 // The channel from the renderer process to the GPU process.
526 scoped_refptr
<GpuChannelHost
> gpu_channel_
;
528 // Cache of variables that are needed on the compositor thread by
529 // GpuChannelHostFactory methods.
530 scoped_refptr
<base::MessageLoopProxy
> io_message_loop_proxy_
;
532 // The message loop of the renderer main thread.
533 // This message loop should be destructed before the RenderThreadImpl
535 scoped_ptr
<base::MessageLoop
> main_message_loop_
;
537 // A lazily initiated thread on which file operations are run.
538 scoped_ptr
<base::Thread
> file_thread_
;
540 // May be null if overridden by ContentRendererClient.
541 scoped_ptr
<base::Thread
> compositor_thread_
;
543 // Thread for running multimedia operations (e.g., video decoding).
544 scoped_ptr
<base::Thread
> media_thread_
;
546 // Will point to appropriate MessageLoopProxy after initialization,
547 // regardless of whether |compositor_thread_| is overriden.
548 scoped_refptr
<base::MessageLoopProxy
> compositor_message_loop_proxy_
;
550 // May be null if unused by the |input_handler_manager_|.
551 scoped_refptr
<InputEventFilter
> input_event_filter_
;
552 scoped_ptr
<InputHandlerManager
> input_handler_manager_
;
553 scoped_refptr
<CompositorForwardingMessageFilter
> compositor_message_filter_
;
555 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
556 shared_main_thread_contexts_
;
558 ObserverList
<RenderProcessObserver
> observers_
;
560 scoped_refptr
<ContextProviderCommandBuffer
> gpu_va_context_provider_
;
562 scoped_ptr
<AudioRendererMixerManager
> audio_renderer_mixer_manager_
;
563 scoped_ptr
<media::AudioHardwareConfig
> audio_hardware_config_
;
565 HistogramCustomizer histogram_customizer_
;
567 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
569 #if defined(ENABLE_WEBRTC)
570 scoped_ptr
<WebRTCIdentityService
> webrtc_identity_service_
;
573 scoped_ptr
<MemoryObserver
> memory_observer_
;
575 scoped_refptr
<base::SingleThreadTaskRunner
>
576 main_thread_compositor_task_runner_
;
578 // Compositor settings
579 bool is_gpu_rasterization_enabled_
;
580 bool is_gpu_rasterization_forced_
;
581 bool is_impl_side_painting_enabled_
;
582 bool is_lcd_text_enabled_
;
583 bool is_distance_field_text_enabled_
;
584 bool is_zero_copy_enabled_
;
585 bool is_one_copy_enabled_
;
586 bool use_image_external_
;
588 std::map
<int, mojo::MessagePipeHandle
> pending_render_frame_connects_
;
590 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl
);
593 } // namespace content
595 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_