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 #if defined(ENABLE_WEBRTC)
276 // Returns a factory used for creating RTC PeerConnection objects.
277 PeerConnectionDependencyFactory* GetPeerConnectionDependencyFactory();
279 PeerConnectionTracker* peer_connection_tracker() {
280 return peer_connection_tracker_.get();
283 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
284 P2PSocketDispatcher* p2p_socket_dispatcher() {
285 return p2p_socket_dispatcher_.get();
289 VideoCaptureImplManager* video_capture_impl_manager() const {
290 return vc_manager_.get();
293 GamepadSharedMemoryReader* gamepad_shared_memory_reader() const {
294 return gamepad_shared_memory_reader_.get();
297 // Get the GPU channel. Returns NULL if the channel is not established or
299 GpuChannelHost* GetGpuChannel();
301 // Returns a MessageLoopProxy instance corresponding to the message loop
302 // of the thread on which file operations should be run. Must be called
303 // on the renderer's main thread.
304 scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
306 // Returns a MessageLoopProxy instance corresponding to the message loop
307 // of the thread on which media operations should be run. Must be called
308 // on the renderer's main thread.
309 scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
311 // Causes the idle handler to skip sending idle notifications
312 // on the two next scheduled calls, so idle notifications are
313 // not sent for at least one notification delay.
314 void PostponeIdleNotification();
316 scoped_refptr<media::GpuVideoAcceleratorFactories> GetGpuFactories();
318 scoped_refptr<webkit::gpu::ContextProviderWebContext>
319 SharedMainThreadContextProvider();
321 // AudioRendererMixerManager instance which manages renderer side mixer
322 // instances shared based on configured audio parameters. Lazily created on
324 AudioRendererMixerManager* GetAudioRendererMixerManager();
326 // AudioHardwareConfig contains audio hardware configuration for
327 // renderer side clients. Creation requires a synchronous IPC call so it is
328 // lazily created on the first call.
329 media::AudioHardwareConfig* GetAudioHardwareConfig();
332 void PreCacheFontCharacters(const LOGFONT& log_font,
333 const base::string16& str);
336 #if defined(ENABLE_WEBRTC)
337 WebRTCIdentityService* get_webrtc_identity_service() {
338 return webrtc_identity_service_.get();
342 // For producing custom V8 histograms. Custom histograms are produced if all
343 // RenderViews share the same host, and the host is in the pre-specified set
344 // of hosts we want to produce custom diagrams for. The name for a custom
345 // diagram is the name of the corresponding generic diagram plus a
346 // host-specific suffix.
347 class CONTENT_EXPORT HistogramCustomizer {
349 HistogramCustomizer();
350 ~HistogramCustomizer();
352 // Called when a top frame of a RenderView navigates. This function updates
353 // RenderThreadImpl's information about whether all RenderViews are
354 // displaying a page from the same host. |host| is the host where a
355 // RenderView navigated, and |view_count| is the number of RenderViews in
357 void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
359 // Used for customizing some histograms if all RenderViews share the same
360 // host. Returns the current custom histogram name to use for
361 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
362 std::string ConvertToCustomHistogramName(const char* histogram_name) const;
365 friend class RenderThreadImplUnittest;
367 // Used for updating the information on which is the common host which all
368 // RenderView's share (if any). If there is no common host, this function is
369 // called with an empty string.
370 void SetCommonHost(const std::string& host);
372 // The current common host of the RenderViews; empty string if there is no
374 std::string common_host_;
375 // The corresponding suffix.
376 std::string common_host_histogram_suffix_;
377 // Set of histograms for which we want to produce a custom histogram if
379 std::set<std::string> custom_histograms_;
381 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
384 HistogramCustomizer* histogram_customizer() {
385 return &histogram_customizer_;
388 void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
389 const std::vector<float>& new_touchscreen);
391 // Retrieve current gamepad data.
392 void SampleGamepads(blink::WebGamepads* data);
394 // Set a listener for gamepad connected/disconnected events.
395 // A non-null listener must be set first before calling SampleGamepads.
396 void SetGamepadListener(blink::WebGamepadListener* listener);
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 virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
415 // GpuChannelHostFactory implementation:
416 virtual bool IsMainThread() OVERRIDE;
417 virtual base::MessageLoop* GetMainLoop() OVERRIDE;
418 virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
419 virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
420 size_t size) OVERRIDE;
421 virtual CreateCommandBufferResult CreateViewCommandBuffer(
423 const GPUCreateCommandBufferConfig& init_params,
424 int32 route_id) OVERRIDE;
425 virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
428 unsigned internalformat,
429 unsigned usage) OVERRIDE;
430 virtual void DeleteGpuMemoryBuffer(
431 scoped_ptr<gfx::GpuMemoryBuffer> buffer) OVERRIDE;
435 void OnCreateNewFrame(int routing_id, int parent_routing_id);
436 void OnCreateNewFrameProxy(int routing_id,
437 int parent_routing_id,
438 int render_view_routing_id);
439 void OnSetZoomLevelForCurrentURL(const std::string& scheme,
440 const std::string& host,
442 void OnCreateNewView(const ViewMsg_New_Params& params);
443 void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
444 void OnPurgePluginListCache(bool reload_pages);
445 void OnNetworkTypeChanged(net::NetworkChangeNotifier::ConnectionType type);
446 void OnGetAccessibilityTree();
447 void OnTempCrashWithData(const GURL& data);
448 void OnUpdateTimezone();
449 void OnMemoryPressure(
450 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
451 #if defined(OS_ANDROID)
452 void OnSetWebKitSharedTimersSuspended(bool suspend);
454 #if defined(OS_MACOSX)
455 void OnUpdateScrollbarTheme(float initial_button_delay,
456 float autoscroll_button_delay,
457 bool jump_on_track_click,
458 blink::ScrollerStyle preferred_scroller_style,
461 void OnCreateNewSharedWorker(
462 const WorkerProcessMsg_CreateWorker_Params& params);
464 void IdleHandlerInForegroundTab();
466 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
468 // These objects live solely on the render thread.
469 scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
470 scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
471 scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
472 scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
473 scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
475 // Used on the render thread and deleted by WebKit at shutdown.
476 blink::WebMediaStreamCenter* media_stream_center_;
478 // Used on the renderer and IPC threads.
479 scoped_refptr<DBMessageFilter> db_message_filter_;
480 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
481 scoped_refptr<AudioMessageFilter> audio_message_filter_;
482 scoped_refptr<MidiMessageFilter> midi_message_filter_;
483 #if defined(OS_ANDROID)
484 scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
486 scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
488 #if defined(ENABLE_WEBRTC)
489 scoped_ptr<PeerConnectionDependencyFactory> peer_connection_factory_;
491 // This is used to communicate to the browser process the status
492 // of all the peer connections created in the renderer.
493 scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
495 // Dispatches all P2P sockets.
496 scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
499 // Used on the render thread.
500 scoped_ptr<VideoCaptureImplManager> vc_manager_;
502 // Used for communicating registering AEC dump consumers with the browser and
503 // receving AEC dump file handles when AEC dump is enabled. An AEC dump is
504 // diagnostic audio data for WebRTC stored locally when enabled by the user in
505 // chrome://webrtc-internals.
506 scoped_refptr<AecDumpMessageFilter> aec_dump_message_filter_;
508 // The count of RenderWidgets running through this thread.
511 // The count of hidden RenderWidgets running through this thread.
512 int hidden_widget_count_;
514 // The current value of the idle notification timer delay.
515 int64 idle_notification_delay_in_ms_;
517 // The number of idle handler calls that skip sending idle notifications.
518 int idle_notifications_to_skip_;
520 bool suspend_webkit_shared_timer_;
521 bool notify_webkit_of_modal_loop_;
522 bool webkit_shared_timer_suspended_;
524 // The following flag is used to control layout test specific behavior.
525 bool layout_test_mode_;
527 // Timer that periodically calls IdleHandler.
528 base::RepeatingTimer<RenderThreadImpl> idle_timer_;
530 // The channel from the renderer process to the GPU process.
531 scoped_refptr<GpuChannelHost> gpu_channel_;
533 // Cache of variables that are needed on the compositor thread by
534 // GpuChannelHostFactory methods.
535 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
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<IPC::ForwardingMessageFilter> compositor_output_surface_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<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
575 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
576 // multiple threads. Current allocation mechanism for IOSurface
577 // backed GpuMemoryBuffers prevent this. crbug.com/325045
578 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_;
580 scoped_ptr<MemoryObserver> memory_observer_;
582 // Compositor settings
583 bool is_gpu_rasterization_enabled_;
584 bool is_gpu_rasterization_forced_;
585 bool is_impl_side_painting_enabled_;
586 bool is_low_res_tiling_enabled_;
587 bool is_lcd_text_enabled_;
588 bool is_distance_field_text_enabled_;
589 bool is_zero_copy_enabled_;
590 bool is_one_copy_enabled_;
592 std::map<int, mojo::MessagePipeHandle> pending_render_frame_connects_;
594 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
597 } // namespace content
599 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_