Removed requirement for the renderer to know it's process ID
[chromium-blink-merge.git] / content / renderer / render_thread_impl.h
blobe948d4c51c404cba8e007360db05add37be40c30
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_
8 #include <set>
9 #include <string>
10 #include <vector>
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 "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
24 #include "ipc/ipc_channel_proxy.h"
25 #include "ui/gfx/native_widget_types.h"
27 class GrContext;
28 class SkBitmap;
29 struct ViewMsg_New_Params;
31 namespace blink {
32 class WebGamepads;
33 class WebGraphicsContext3D;
34 class WebMediaStreamCenter;
35 class WebMediaStreamCenterClient;
38 namespace base {
39 class MessageLoopProxy;
40 class Thread;
43 namespace cc {
44 class ContextProvider;
47 namespace IPC {
48 class ForwardingMessageFilter;
51 namespace media {
52 class AudioHardwareConfig;
55 namespace v8 {
56 class Extension;
59 namespace webkit {
60 namespace gpu {
61 class ContextProviderWebContext;
62 class GrContextForWebGraphicsContext3D;
66 namespace content {
68 class AppCacheDispatcher;
69 class AudioInputMessageFilter;
70 class AudioMessageFilter;
71 class AudioRendererMixerManager;
72 class ContextProviderCommandBuffer;
73 class DBMessageFilter;
74 class DevToolsAgentFilter;
75 class DomStorageDispatcher;
76 class EmbeddedWorkerDispatcher;
77 class GamepadSharedMemoryReader;
78 class GpuChannelHost;
79 class IndexedDBDispatcher;
80 class InputEventFilter;
81 class InputHandlerManager;
82 class MediaStreamCenter;
83 class MediaStreamDependencyFactory;
84 class MIDIMessageFilter;
85 class P2PSocketDispatcher;
86 class PeerConnectionTracker;
87 class RendererDemuxerAndroid;
88 class RendererWebKitPlatformSupportImpl;
89 class RenderProcessObserver;
90 class VideoCaptureImplManager;
91 class WebGraphicsContext3DCommandBufferImpl;
92 class WebRTCIdentityService;
94 // The RenderThreadImpl class represents a background thread where RenderView
95 // instances live. The RenderThread supports an API that is used by its
96 // consumer to talk indirectly to the RenderViews and supporting objects.
97 // Likewise, it provides an API for the RenderViews to talk back to the main
98 // process (i.e., their corresponding WebContentsImpl).
100 // Most of the communication occurs in the form of IPC messages. They are
101 // routed to the RenderThread according to the routing IDs of the messages.
102 // The routing IDs correspond to RenderView instances.
103 class CONTENT_EXPORT RenderThreadImpl : public RenderThread,
104 public ChildThread,
105 public GpuChannelHostFactory {
106 public:
107 static RenderThreadImpl* current();
109 RenderThreadImpl();
110 // Constructor that's used when running in single process mode.
111 explicit RenderThreadImpl(const std::string& channel_name);
112 virtual ~RenderThreadImpl();
113 virtual void Shutdown() OVERRIDE;
115 // When initializing WebKit, ensure that any schemes needed for the content
116 // module are registered properly. Static to allow sharing with tests.
117 static void RegisterSchemes();
119 // RenderThread implementation:
120 virtual bool Send(IPC::Message* msg) OVERRIDE;
121 virtual base::MessageLoop* GetMessageLoop() OVERRIDE;
122 virtual IPC::SyncChannel* GetChannel() OVERRIDE;
123 virtual std::string GetLocale() OVERRIDE;
124 virtual IPC::SyncMessageFilter* GetSyncMessageFilter() OVERRIDE;
125 virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy()
126 OVERRIDE;
127 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
128 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
129 virtual int GenerateRoutingID() OVERRIDE;
130 virtual void AddFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
131 virtual void RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
132 virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
133 virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
134 virtual void SetResourceDispatcherDelegate(
135 ResourceDispatcherDelegate* delegate) OVERRIDE;
136 virtual void EnsureWebKitInitialized() OVERRIDE;
137 virtual void RecordAction(const base::UserMetricsAction& action) OVERRIDE;
138 virtual void RecordComputedAction(const std::string& action) OVERRIDE;
139 virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
140 size_t buffer_size) OVERRIDE;
141 virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
142 virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
143 virtual void IdleHandler() OVERRIDE;
144 virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
145 virtual void SetIdleNotificationDelayInMs(
146 int64 idle_notification_delay_in_ms) OVERRIDE;
147 virtual void UpdateHistograms(int sequence_number) OVERRIDE;
148 virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
149 virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
150 #if defined(OS_WIN)
151 virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
152 virtual void ReleaseCachedFonts() OVERRIDE;
153 #endif
155 // Synchronously establish a channel to the GPU plugin if not previously
156 // established or if it has been lost (for example if the GPU plugin crashed).
157 // If there is a pending asynchronous request, it will be completed by the
158 // time this routine returns.
159 GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
162 // These methods modify how the next message is sent. Normally, when sending
163 // a synchronous message that runs a nested message loop, we need to suspend
164 // callbacks into WebKit. This involves disabling timers and deferring
165 // resource loads. However, there are exceptions when we need to customize
166 // the behavior.
167 void DoNotSuspendWebKitSharedTimer();
168 void DoNotNotifyWebKitOfModalLoop();
170 // True if we are running layout tests. This currently disables forwarding
171 // various status messages to the console, skips network error pages, and
172 // short circuits size update and focus events.
173 bool layout_test_mode() const {
174 return layout_test_mode_;
176 void set_layout_test_mode(bool layout_test_mode) {
177 layout_test_mode_ = layout_test_mode;
180 IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
181 return compositor_output_surface_filter_.get();
184 InputHandlerManager* input_handler_manager() const {
185 return input_handler_manager_.get();
188 // Will be NULL if threaded compositing has not been enabled.
189 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
190 return compositor_message_loop_proxy_;
193 AppCacheDispatcher* appcache_dispatcher() const {
194 return appcache_dispatcher_.get();
197 DomStorageDispatcher* dom_storage_dispatcher() const {
198 return dom_storage_dispatcher_.get();
201 EmbeddedWorkerDispatcher* embedded_worker_dispatcher() const {
202 return embedded_worker_dispatcher_.get();
205 AudioInputMessageFilter* audio_input_message_filter() {
206 return audio_input_message_filter_.get();
209 AudioMessageFilter* audio_message_filter() {
210 return audio_message_filter_.get();
213 MIDIMessageFilter* midi_message_filter() {
214 return midi_message_filter_.get();
217 #if defined(OS_ANDROID)
218 RendererDemuxerAndroid* renderer_demuxer() {
219 return renderer_demuxer_.get();
221 #endif
223 // Creates the embedder implementation of WebMediaStreamCenter.
224 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
225 blink::WebMediaStreamCenter* CreateMediaStreamCenter(
226 blink::WebMediaStreamCenterClient* client);
228 // Returns a factory used for creating RTC PeerConnection objects.
229 MediaStreamDependencyFactory* GetMediaStreamDependencyFactory();
231 PeerConnectionTracker* peer_connection_tracker() {
232 return peer_connection_tracker_.get();
235 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
236 P2PSocketDispatcher* p2p_socket_dispatcher() {
237 return p2p_socket_dispatcher_.get();
240 VideoCaptureImplManager* video_capture_impl_manager() const {
241 return vc_manager_.get();
244 // Get the GPU channel. Returns NULL if the channel is not established or
245 // has been lost.
246 GpuChannelHost* GetGpuChannel();
248 // Returns a MessageLoopProxy instance corresponding to the message loop
249 // of the thread on which file operations should be run. Must be called
250 // on the renderer's main thread.
251 scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
253 // Returns a MessageLoopProxy instance corresponding to the message loop
254 // of the thread on which media operations should be run. Must be called
255 // on the renderer's main thread.
256 scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
258 // Causes the idle handler to skip sending idle notifications
259 // on the two next scheduled calls, so idle notifications are
260 // not sent for at least one notification delay.
261 void PostponeIdleNotification();
263 scoped_refptr<RendererGpuVideoAcceleratorFactories> GetGpuFactories();
265 scoped_refptr<cc::ContextProvider> OffscreenCompositorContextProvider();
266 scoped_refptr<webkit::gpu::ContextProviderWebContext>
267 SharedMainThreadContextProvider();
269 // AudioRendererMixerManager instance which manages renderer side mixer
270 // instances shared based on configured audio parameters. Lazily created on
271 // first call.
272 AudioRendererMixerManager* GetAudioRendererMixerManager();
274 // AudioHardwareConfig contains audio hardware configuration for
275 // renderer side clients. Creation requires a synchronous IPC call so it is
276 // lazily created on the first call.
277 media::AudioHardwareConfig* GetAudioHardwareConfig();
279 #if defined(OS_WIN)
280 void PreCacheFontCharacters(const LOGFONT& log_font,
281 const base::string16& str);
282 #endif
284 #if defined(ENABLE_WEBRTC)
285 WebRTCIdentityService* get_webrtc_identity_service() {
286 return webrtc_identity_service_.get();
288 #endif
290 // For producing custom V8 histograms. Custom histograms are produced if all
291 // RenderViews share the same host, and the host is in the pre-specified set
292 // of hosts we want to produce custom diagrams for. The name for a custom
293 // diagram is the name of the corresponding generic diagram plus a
294 // host-specific suffix.
295 class CONTENT_EXPORT HistogramCustomizer {
296 public:
297 HistogramCustomizer();
298 ~HistogramCustomizer();
300 // Called when a top frame of a RenderView navigates. This function updates
301 // RenderThreadImpl's information about whether all RenderViews are
302 // displaying a page from the same host. |host| is the host where a
303 // RenderView navigated, and |view_count| is the number of RenderViews in
304 // this process.
305 void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
307 // Used for customizing some histograms if all RenderViews share the same
308 // host. Returns the current custom histogram name to use for
309 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
310 std::string ConvertToCustomHistogramName(const char* histogram_name) const;
312 private:
313 friend class RenderThreadImplUnittest;
315 // Used for updating the information on which is the common host which all
316 // RenderView's share (if any). If there is no common host, this function is
317 // called with an empty string.
318 void SetCommonHost(const std::string& host);
320 // The current common host of the RenderViews; empty string if there is no
321 // common host.
322 std::string common_host_;
323 // The corresponding suffix.
324 std::string common_host_histogram_suffix_;
325 // Set of histograms for which we want to produce a custom histogram if
326 // possible.
327 std::set<std::string> custom_histograms_;
329 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
332 HistogramCustomizer* histogram_customizer() {
333 return &histogram_customizer_;
336 void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
337 const std::vector<float>& new_touchscreen);
339 // Retrieve current gamepad data.
340 void SampleGamepads(blink::WebGamepads* data);
342 // Called by a RenderWidget when it is created or destroyed. This
343 // allows the process to know when there are no visible widgets.
344 void WidgetCreated();
345 void WidgetDestroyed();
346 void WidgetHidden();
347 void WidgetRestored();
349 private:
350 // ChildThread
351 virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
353 // GpuChannelHostFactory implementation:
354 virtual bool IsMainThread() OVERRIDE;
355 virtual base::MessageLoop* GetMainLoop() OVERRIDE;
356 virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
357 virtual base::WaitableEvent* GetShutDownEvent() OVERRIDE;
358 virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
359 size_t size) OVERRIDE;
360 virtual int32 CreateViewCommandBuffer(
361 int32 surface_id,
362 const GPUCreateCommandBufferConfig& init_params) OVERRIDE;
363 virtual void CreateImage(
364 gfx::PluginWindowHandle window,
365 int32 image_id,
366 const CreateImageCallback& callback) OVERRIDE;
367 virtual void DeleteImage(int32 image_id, int32 sync_point) OVERRIDE;
368 virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
369 size_t width,
370 size_t height,
371 unsigned internalformat) OVERRIDE;
373 void Init();
375 void OnSetZoomLevelForCurrentURL(const std::string& scheme,
376 const std::string& host,
377 double zoom_level);
378 void OnCreateNewView(const ViewMsg_New_Params& params);
379 void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
380 void OnPurgePluginListCache(bool reload_pages);
381 void OnNetworkStateChanged(bool online);
382 void OnGetAccessibilityTree();
383 void OnTempCrashWithData(const GURL& data);
384 void OnMemoryPressure(
385 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
386 #if defined(OS_ANDROID)
387 void OnSetWebKitSharedTimersSuspended(bool suspend);
388 #endif
389 #if defined(OS_MACOSX)
390 void OnUpdateScrollbarTheme(float initial_button_delay,
391 float autoscroll_button_delay,
392 bool jump_on_track_click,
393 bool redraw);
394 #endif
396 void IdleHandlerInForegroundTab();
398 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
400 // These objects live solely on the render thread.
401 scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
402 scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
403 scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
404 scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
405 scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
407 // Used on the render thread and deleted by WebKit at shutdown.
408 blink::WebMediaStreamCenter* media_stream_center_;
410 // Used on the renderer and IPC threads.
411 scoped_refptr<DBMessageFilter> db_message_filter_;
412 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
413 scoped_refptr<AudioMessageFilter> audio_message_filter_;
414 scoped_refptr<MIDIMessageFilter> midi_message_filter_;
415 #if defined(OS_ANDROID)
416 scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
417 #endif
418 scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
420 scoped_ptr<MediaStreamDependencyFactory> media_stream_factory_;
422 // This is used to communicate to the browser process the status
423 // of all the peer connections created in the renderer.
424 scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
426 // Dispatches all P2P sockets.
427 scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
429 // Used on the render thread.
430 scoped_ptr<VideoCaptureImplManager> vc_manager_;
432 // The count of RenderWidgets running through this thread.
433 int widget_count_;
435 // The count of hidden RenderWidgets running through this thread.
436 int hidden_widget_count_;
438 // The current value of the idle notification timer delay.
439 int64 idle_notification_delay_in_ms_;
441 // The number of idle handler calls that skip sending idle notifications.
442 int idle_notifications_to_skip_;
444 bool suspend_webkit_shared_timer_;
445 bool notify_webkit_of_modal_loop_;
446 bool webkit_shared_timer_suspended_;
448 // The following flag is used to control layout test specific behavior.
449 bool layout_test_mode_;
451 // Timer that periodically calls IdleHandler.
452 base::RepeatingTimer<RenderThreadImpl> idle_timer_;
454 // The channel from the renderer process to the GPU process.
455 scoped_refptr<GpuChannelHost> gpu_channel_;
457 // Cache of variables that are needed on the compositor thread by
458 // GpuChannelHostFactory methods.
459 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
460 base::WaitableEvent* shutdown_event_;
462 // A lazily initiated thread on which file operations are run.
463 scoped_ptr<base::Thread> file_thread_;
465 // May be null if overridden by ContentRendererClient.
466 scoped_ptr<base::Thread> compositor_thread_;
468 // Thread for running multimedia operations (e.g., video decoding).
469 scoped_ptr<base::Thread> media_thread_;
471 // Will point to appropriate MessageLoopProxy after initialization,
472 // regardless of whether |compositor_thread_| is overriden.
473 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
475 // May be null if unused by the |input_handler_manager_|.
476 scoped_refptr<InputEventFilter> input_event_filter_;
477 scoped_ptr<InputHandlerManager> input_handler_manager_;
478 scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
480 scoped_refptr<ContextProviderCommandBuffer> offscreen_compositor_contexts_;
481 scoped_refptr<ContextProviderCommandBuffer> shared_main_thread_contexts_;
483 ObserverList<RenderProcessObserver> observers_;
485 scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
487 scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
488 scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
490 HistogramCustomizer histogram_customizer_;
492 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
494 scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
496 scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
498 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
499 // multiple threads. Current allocation mechanism for IOSurface
500 // backed GpuMemoryBuffers prevent this. crbug.com/325045
501 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_;
503 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
506 } // namespace content
508 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_