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;
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;
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 ~RenderThreadImpl() override;
125 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 bool Send(IPC::Message* msg) override;
137 base::MessageLoop* GetMessageLoop() override;
138 IPC::SyncChannel* GetChannel() override;
139 std::string GetLocale() override;
140 IPC::SyncMessageFilter* GetSyncMessageFilter() override;
141 scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() override;
142 void AddRoute(int32 routing_id, IPC::Listener* listener) override;
143 void RemoveRoute(int32 routing_id) override;
144 int GenerateRoutingID() override;
145 void AddFilter(IPC::MessageFilter* filter) override;
146 void RemoveFilter(IPC::MessageFilter* filter) override;
147 void AddObserver(RenderProcessObserver* observer) override;
148 void RemoveObserver(RenderProcessObserver* observer) override;
149 void SetResourceDispatcherDelegate(
150 ResourceDispatcherDelegate* delegate) override;
151 void EnsureWebKitInitialized() override;
152 void RecordAction(const base::UserMetricsAction& action) override;
153 void RecordComputedAction(const std::string& action) override;
154 scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
155 size_t buffer_size) override;
156 void RegisterExtension(v8::Extension* extension) override;
157 void ScheduleIdleHandler(int64 initial_delay_ms) override;
158 void IdleHandler() override;
159 int64 GetIdleNotificationDelayInMs() const override;
160 void SetIdleNotificationDelayInMs(
161 int64 idle_notification_delay_in_ms) override;
162 void UpdateHistograms(int sequence_number) override;
163 int PostTaskToAllWebWorkers(const base::Closure& closure) override;
164 bool ResolveProxy(const GURL& url, std::string* proxy_list) override;
165 base::WaitableEvent* GetShutdownEvent() override;
167 virtual void PreCacheFont(const LOGFONT& log_font) override;
168 virtual void ReleaseCachedFonts() override;
170 ServiceRegistry* GetServiceRegistry() override;
172 // Synchronously establish a channel to the GPU plugin if not previously
173 // established or if it has been lost (for example if the GPU plugin crashed).
174 // If there is a pending asynchronous request, it will be completed by the
175 // time this routine returns.
176 GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
179 // These methods modify how the next message is sent. Normally, when sending
180 // a synchronous message that runs a nested message loop, we need to suspend
181 // callbacks into WebKit. This involves disabling timers and deferring
182 // resource loads. However, there are exceptions when we need to customize
184 void DoNotSuspendWebKitSharedTimer();
185 void DoNotNotifyWebKitOfModalLoop();
187 // True if we are running layout tests. This currently disables forwarding
188 // various status messages to the console, skips network error pages, and
189 // short circuits size update and focus events.
190 bool layout_test_mode() const {
191 return layout_test_mode_;
193 void set_layout_test_mode(bool layout_test_mode) {
194 layout_test_mode_ = layout_test_mode;
197 RendererScheduler* renderer_scheduler() const {
198 DCHECK(renderer_scheduler_);
199 return renderer_scheduler_.get();
202 RendererBlinkPlatformImpl* blink_platform_impl() const {
203 DCHECK(blink_platform_impl_);
204 return blink_platform_impl_.get();
207 scoped_refptr<base::SingleThreadTaskRunner>
208 main_thread_compositor_task_runner() const {
209 return main_thread_compositor_task_runner_;
212 IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
213 return compositor_output_surface_filter_.get();
216 InputHandlerManager* input_handler_manager() const {
217 return input_handler_manager_.get();
220 // Will be NULL if threaded compositing has not been enabled.
221 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
222 return compositor_message_loop_proxy_;
225 bool is_gpu_rasterization_enabled() const {
226 return is_gpu_rasterization_enabled_;
229 bool is_gpu_rasterization_forced() const {
230 return is_gpu_rasterization_forced_;
233 bool is_impl_side_painting_enabled() const {
234 return is_impl_side_painting_enabled_;
237 bool is_lcd_text_enabled() const { return is_lcd_text_enabled_; }
239 bool is_distance_field_text_enabled() const {
240 return is_distance_field_text_enabled_;
243 bool is_zero_copy_enabled() const { return is_zero_copy_enabled_; }
245 bool is_one_copy_enabled() const { return is_one_copy_enabled_; }
247 AppCacheDispatcher* appcache_dispatcher() const {
248 return appcache_dispatcher_.get();
251 DomStorageDispatcher* dom_storage_dispatcher() const {
252 return dom_storage_dispatcher_.get();
255 EmbeddedWorkerDispatcher* embedded_worker_dispatcher() const {
256 return embedded_worker_dispatcher_.get();
259 AudioInputMessageFilter* audio_input_message_filter() {
260 return audio_input_message_filter_.get();
263 AudioMessageFilter* audio_message_filter() {
264 return audio_message_filter_.get();
267 MidiMessageFilter* midi_message_filter() {
268 return midi_message_filter_.get();
271 #if defined(OS_ANDROID)
272 RendererDemuxerAndroid* renderer_demuxer() {
273 return renderer_demuxer_.get();
277 // Creates the embedder implementation of WebMediaStreamCenter.
278 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
279 blink::WebMediaStreamCenter* CreateMediaStreamCenter(
280 blink::WebMediaStreamCenterClient* client);
282 #if defined(ENABLE_WEBRTC)
283 // Returns a factory used for creating RTC PeerConnection objects.
284 PeerConnectionDependencyFactory* GetPeerConnectionDependencyFactory();
286 PeerConnectionTracker* peer_connection_tracker() {
287 return peer_connection_tracker_.get();
290 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
291 P2PSocketDispatcher* p2p_socket_dispatcher() {
292 return p2p_socket_dispatcher_.get();
296 VideoCaptureImplManager* video_capture_impl_manager() const {
297 return vc_manager_.get();
300 // Get the GPU channel. Returns NULL if the channel is not established or
302 GpuChannelHost* GetGpuChannel();
304 // Returns a MessageLoopProxy instance corresponding to the message loop
305 // of the thread on which file operations should be run. Must be called
306 // on the renderer's main thread.
307 scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
309 // Returns a SingleThreadTaskRunner instance corresponding to the message loop
310 // of the thread on which media operations should be run. Must be called
311 // on the renderer's main thread.
312 scoped_refptr<base::SingleThreadTaskRunner> GetMediaThreadTaskRunner();
314 // Causes the idle handler to skip sending idle notifications
315 // on the two next scheduled calls, so idle notifications are
316 // not sent for at least one notification delay.
317 void PostponeIdleNotification();
319 scoped_refptr<media::GpuVideoAcceleratorFactories> GetGpuFactories();
321 scoped_refptr<webkit::gpu::ContextProviderWebContext>
322 SharedMainThreadContextProvider();
324 // AudioRendererMixerManager instance which manages renderer side mixer
325 // instances shared based on configured audio parameters. Lazily created on
327 AudioRendererMixerManager* GetAudioRendererMixerManager();
329 // AudioHardwareConfig contains audio hardware configuration for
330 // renderer side clients. Creation requires a synchronous IPC call so it is
331 // lazily created on the first call.
332 media::AudioHardwareConfig* GetAudioHardwareConfig();
335 void PreCacheFontCharacters(const LOGFONT& log_font,
336 const base::string16& str);
339 #if defined(ENABLE_WEBRTC)
340 WebRTCIdentityService* get_webrtc_identity_service() {
341 return webrtc_identity_service_.get();
345 // For producing custom V8 histograms. Custom histograms are produced if all
346 // RenderViews share the same host, and the host is in the pre-specified set
347 // of hosts we want to produce custom diagrams for. The name for a custom
348 // diagram is the name of the corresponding generic diagram plus a
349 // host-specific suffix.
350 class CONTENT_EXPORT HistogramCustomizer {
352 HistogramCustomizer();
353 ~HistogramCustomizer();
355 // Called when a top frame of a RenderView navigates. This function updates
356 // RenderThreadImpl's information about whether all RenderViews are
357 // displaying a page from the same host. |host| is the host where a
358 // RenderView navigated, and |view_count| is the number of RenderViews in
360 void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
362 // Used for customizing some histograms if all RenderViews share the same
363 // host. Returns the current custom histogram name to use for
364 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
365 std::string ConvertToCustomHistogramName(const char* histogram_name) const;
368 friend class RenderThreadImplUnittest;
370 // Used for updating the information on which is the common host which all
371 // RenderView's share (if any). If there is no common host, this function is
372 // called with an empty string.
373 void SetCommonHost(const std::string& host);
375 // The current common host of the RenderViews; empty string if there is no
377 std::string common_host_;
378 // The corresponding suffix.
379 std::string common_host_histogram_suffix_;
380 // Set of histograms for which we want to produce a custom histogram if
382 std::set<std::string> custom_histograms_;
384 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
387 HistogramCustomizer* histogram_customizer() {
388 return &histogram_customizer_;
391 // Retrieve current gamepad data.
392 void SampleGamepads(blink::WebGamepads* data);
394 // Called by a RenderWidget when it is created or destroyed. This
395 // allows the process to know when there are no visible widgets.
396 void WidgetCreated();
397 void WidgetDestroyed();
399 void WidgetRestored();
401 void AddEmbeddedWorkerRoute(int32 routing_id, IPC::Listener* listener);
402 void RemoveEmbeddedWorkerRoute(int32 routing_id);
404 void RegisterPendingRenderFrameConnect(int routing_id,
405 mojo::ScopedMessagePipeHandle handle);
409 bool OnControlMessageReceived(const IPC::Message& msg) override;
411 // GpuChannelHostFactory implementation:
412 bool IsMainThread() override;
413 base::MessageLoop* GetMainLoop() override;
414 scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() override;
415 scoped_ptr<base::SharedMemory> AllocateSharedMemory(size_t size) override;
416 CreateCommandBufferResult CreateViewCommandBuffer(
418 const GPUCreateCommandBufferConfig& init_params,
419 int32 route_id) override;
423 void OnCreateNewFrame(int routing_id,
424 int parent_routing_id,
425 int proxy_routing_id);
426 void OnCreateNewFrameProxy(int routing_id,
427 int parent_routing_id,
428 int render_view_routing_id);
429 void OnSetZoomLevelForCurrentURL(const std::string& scheme,
430 const std::string& host,
432 void OnCreateNewView(const ViewMsg_New_Params& params);
433 void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
434 #if defined(ENABLE_PLUGINS)
435 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 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
458 // These objects live solely on the render thread.
459 scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
460 scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
461 scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
462 scoped_ptr<RendererScheduler> renderer_scheduler_;
463 scoped_ptr<RendererBlinkPlatformImpl> blink_platform_impl_;
464 scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
466 // Used on the render thread and deleted by WebKit at shutdown.
467 blink::WebMediaStreamCenter* media_stream_center_;
469 // Used on the renderer and IPC threads.
470 scoped_refptr<DBMessageFilter> db_message_filter_;
471 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
472 scoped_refptr<AudioMessageFilter> audio_message_filter_;
473 scoped_refptr<MidiMessageFilter> midi_message_filter_;
474 #if defined(OS_ANDROID)
475 scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
477 scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
479 #if defined(ENABLE_WEBRTC)
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_;
490 // Used on the render thread.
491 scoped_ptr<VideoCaptureImplManager> vc_manager_;
493 // Used for communicating registering AEC dump consumers with the browser and
494 // receving AEC dump file handles when AEC dump is enabled. An AEC dump is
495 // diagnostic audio data for WebRTC stored locally when enabled by the user in
496 // chrome://webrtc-internals.
497 scoped_refptr<AecDumpMessageFilter> aec_dump_message_filter_;
499 // The count of RenderWidgets running through this thread.
502 // The count of hidden RenderWidgets running through this thread.
503 int hidden_widget_count_;
505 // The current value of the idle notification timer delay.
506 int64 idle_notification_delay_in_ms_;
508 // The number of idle handler calls that skip sending idle notifications.
509 int idle_notifications_to_skip_;
511 bool suspend_webkit_shared_timer_;
512 bool notify_webkit_of_modal_loop_;
513 bool webkit_shared_timer_suspended_;
515 // The following flag is used to control layout test specific behavior.
516 bool layout_test_mode_;
518 // Timer that periodically calls IdleHandler.
519 base::RepeatingTimer<RenderThreadImpl> idle_timer_;
521 // The channel from the renderer process to the GPU process.
522 scoped_refptr<GpuChannelHost> gpu_channel_;
524 // Cache of variables that are needed on the compositor thread by
525 // GpuChannelHostFactory methods.
526 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
528 // A lazily initiated thread on which file operations are run.
529 scoped_ptr<base::Thread> file_thread_;
531 // May be null if overridden by ContentRendererClient.
532 scoped_ptr<base::Thread> compositor_thread_;
534 // Thread for running multimedia operations (e.g., video decoding).
535 scoped_ptr<base::Thread> media_thread_;
537 // Will point to appropriate MessageLoopProxy after initialization,
538 // regardless of whether |compositor_thread_| is overriden.
539 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
541 // May be null if unused by the |input_handler_manager_|.
542 scoped_refptr<InputEventFilter> input_event_filter_;
543 scoped_ptr<InputHandlerManager> input_handler_manager_;
544 scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
546 scoped_refptr<webkit::gpu::ContextProviderWebContext>
547 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 #if defined(ENABLE_WEBRTC)
561 scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
564 scoped_ptr<MemoryObserver> memory_observer_;
566 scoped_refptr<base::SingleThreadTaskRunner>
567 main_thread_compositor_task_runner_;
569 // Compositor settings
570 bool is_gpu_rasterization_enabled_;
571 bool is_gpu_rasterization_forced_;
572 bool is_impl_side_painting_enabled_;
573 bool is_lcd_text_enabled_;
574 bool is_distance_field_text_enabled_;
575 bool is_zero_copy_enabled_;
576 bool is_one_copy_enabled_;
578 std::map<int, mojo::MessagePipeHandle> pending_render_frame_connects_;
580 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
583 } // namespace content
585 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_