Shell / ShellClient -> ServiceProvider
[chromium-blink-merge.git] / content / renderer / render_thread_impl.h
blobd6c3a8932a5e0946cf30d364643e4cf14dbd3cda
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 "ui/gfx/native_widget_types.h"
25 #if defined(OS_MACOSX)
26 #include "third_party/WebKit/public/web/mac/WebScrollbarTheme.h"
27 #endif
29 class GrContext;
30 class SkBitmap;
31 struct ViewMsg_New_Params;
32 struct WorkerProcessMsg_CreateWorker_Params;
34 namespace blink {
35 class WebGamepads;
36 class WebGamepadListener;
37 class WebGraphicsContext3D;
38 class WebMediaStreamCenter;
39 class WebMediaStreamCenterClient;
42 namespace base {
43 class MessageLoopProxy;
44 class Thread;
47 namespace cc {
48 class ContextProvider;
51 namespace IPC {
52 class ForwardingMessageFilter;
53 class MessageFilter;
56 namespace media {
57 class AudioHardwareConfig;
58 class GpuVideoAcceleratorFactories;
61 namespace v8 {
62 class Extension;
65 namespace webkit {
66 namespace gpu {
67 class ContextProviderWebContext;
68 class GrContextForWebGraphicsContext3D;
72 namespace content {
74 class AppCacheDispatcher;
75 class AudioInputMessageFilter;
76 class AudioMessageFilter;
77 class AudioRendererMixerManager;
78 class ContextProviderCommandBuffer;
79 class DBMessageFilter;
80 class DevToolsAgentFilter;
81 class DomStorageDispatcher;
82 class EmbeddedWorkerDispatcher;
83 class GamepadSharedMemoryReader;
84 class GpuChannelHost;
85 class IndexedDBDispatcher;
86 class InputEventFilter;
87 class InputHandlerManager;
88 class MediaStreamCenter;
89 class PeerConnectionDependencyFactory;
90 class MidiMessageFilter;
91 class P2PSocketDispatcher;
92 class PeerConnectionTracker;
93 class RendererDemuxerAndroid;
94 class RendererWebKitPlatformSupportImpl;
95 class RenderProcessObserver;
96 class VideoCaptureImplManager;
97 class WebGraphicsContext3DCommandBufferImpl;
98 class WebRTCIdentityService;
100 // The RenderThreadImpl class represents a background thread where RenderView
101 // instances live. The RenderThread supports an API that is used by its
102 // consumer to talk indirectly to the RenderViews and supporting objects.
103 // Likewise, it provides an API for the RenderViews to talk back to the main
104 // process (i.e., their corresponding WebContentsImpl).
106 // Most of the communication occurs in the form of IPC messages. They are
107 // routed to the RenderThread according to the routing IDs of the messages.
108 // The routing IDs correspond to RenderView instances.
109 class CONTENT_EXPORT RenderThreadImpl : public RenderThread,
110 public ChildThread,
111 public GpuChannelHostFactory {
112 public:
113 static RenderThreadImpl* current();
115 RenderThreadImpl();
116 // Constructor that's used when running in single process mode.
117 explicit RenderThreadImpl(const std::string& channel_name);
118 virtual ~RenderThreadImpl();
119 virtual void Shutdown() OVERRIDE;
121 // When initializing WebKit, ensure that any schemes needed for the content
122 // module are registered properly. Static to allow sharing with tests.
123 static void RegisterSchemes();
125 // Notify V8 that the date/time configuration of the system might have
126 // changed.
127 static void NotifyTimezoneChange();
129 // RenderThread implementation:
130 virtual bool Send(IPC::Message* msg) OVERRIDE;
131 virtual base::MessageLoop* GetMessageLoop() OVERRIDE;
132 virtual IPC::SyncChannel* GetChannel() OVERRIDE;
133 virtual std::string GetLocale() OVERRIDE;
134 virtual IPC::SyncMessageFilter* GetSyncMessageFilter() OVERRIDE;
135 virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy()
136 OVERRIDE;
137 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
138 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
139 virtual int GenerateRoutingID() OVERRIDE;
140 virtual void AddFilter(IPC::MessageFilter* filter) OVERRIDE;
141 virtual void RemoveFilter(IPC::MessageFilter* filter) OVERRIDE;
142 virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
143 virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
144 virtual void SetResourceDispatcherDelegate(
145 ResourceDispatcherDelegate* delegate) OVERRIDE;
146 virtual void EnsureWebKitInitialized() OVERRIDE;
147 virtual void RecordAction(const base::UserMetricsAction& action) OVERRIDE;
148 virtual void RecordComputedAction(const std::string& action) OVERRIDE;
149 virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
150 size_t buffer_size) OVERRIDE;
151 virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
152 virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
153 virtual void IdleHandler() OVERRIDE;
154 virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
155 virtual void SetIdleNotificationDelayInMs(
156 int64 idle_notification_delay_in_ms) OVERRIDE;
157 virtual void UpdateHistograms(int sequence_number) OVERRIDE;
158 virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
159 virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
160 virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE;
161 #if defined(OS_WIN)
162 virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
163 virtual void ReleaseCachedFonts() OVERRIDE;
164 #endif
166 // Synchronously establish a channel to the GPU plugin if not previously
167 // established or if it has been lost (for example if the GPU plugin crashed).
168 // If there is a pending asynchronous request, it will be completed by the
169 // time this routine returns.
170 GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
173 // These methods modify how the next message is sent. Normally, when sending
174 // a synchronous message that runs a nested message loop, we need to suspend
175 // callbacks into WebKit. This involves disabling timers and deferring
176 // resource loads. However, there are exceptions when we need to customize
177 // the behavior.
178 void DoNotSuspendWebKitSharedTimer();
179 void DoNotNotifyWebKitOfModalLoop();
181 // True if we are running layout tests. This currently disables forwarding
182 // various status messages to the console, skips network error pages, and
183 // short circuits size update and focus events.
184 bool layout_test_mode() const {
185 return layout_test_mode_;
187 void set_layout_test_mode(bool layout_test_mode) {
188 layout_test_mode_ = layout_test_mode;
191 IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
192 return compositor_output_surface_filter_.get();
195 InputHandlerManager* input_handler_manager() const {
196 return input_handler_manager_.get();
199 // Will be NULL if threaded compositing has not been enabled.
200 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
201 return compositor_message_loop_proxy_;
204 bool is_gpu_rasterization_enabled() const {
205 return is_gpu_rasterization_enabled_;
208 bool is_gpu_rasterization_forced() const {
209 return is_gpu_rasterization_forced_;
212 bool is_impl_side_painting_enabled() const {
213 return is_impl_side_painting_enabled_;
216 bool is_low_res_tiling_enabled() const { return is_low_res_tiling_enabled_; }
218 bool is_lcd_text_enabled() const { return is_lcd_text_enabled_; }
220 bool is_distance_field_text_enabled() const {
221 return is_distance_field_text_enabled_;
224 bool is_zero_copy_enabled() const { return is_zero_copy_enabled_; }
226 bool is_one_copy_enabled() const { return is_one_copy_enabled_; }
228 AppCacheDispatcher* appcache_dispatcher() const {
229 return appcache_dispatcher_.get();
232 DomStorageDispatcher* dom_storage_dispatcher() const {
233 return dom_storage_dispatcher_.get();
236 EmbeddedWorkerDispatcher* embedded_worker_dispatcher() const {
237 return embedded_worker_dispatcher_.get();
240 AudioInputMessageFilter* audio_input_message_filter() {
241 return audio_input_message_filter_.get();
244 AudioMessageFilter* audio_message_filter() {
245 return audio_message_filter_.get();
248 MidiMessageFilter* midi_message_filter() {
249 return midi_message_filter_.get();
252 #if defined(OS_ANDROID)
253 RendererDemuxerAndroid* renderer_demuxer() {
254 return renderer_demuxer_.get();
256 #endif
258 // Creates the embedder implementation of WebMediaStreamCenter.
259 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
260 blink::WebMediaStreamCenter* CreateMediaStreamCenter(
261 blink::WebMediaStreamCenterClient* client);
263 // Returns a factory used for creating RTC PeerConnection objects.
264 PeerConnectionDependencyFactory* GetPeerConnectionDependencyFactory();
266 PeerConnectionTracker* peer_connection_tracker() {
267 return peer_connection_tracker_.get();
270 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
271 P2PSocketDispatcher* p2p_socket_dispatcher() {
272 return p2p_socket_dispatcher_.get();
275 VideoCaptureImplManager* video_capture_impl_manager() const {
276 return vc_manager_.get();
279 GamepadSharedMemoryReader* gamepad_shared_memory_reader() const {
280 return gamepad_shared_memory_reader_.get();
283 // Get the GPU channel. Returns NULL if the channel is not established or
284 // has been lost.
285 GpuChannelHost* GetGpuChannel();
287 // Returns a MessageLoopProxy instance corresponding to the message loop
288 // of the thread on which file operations should be run. Must be called
289 // on the renderer's main thread.
290 scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
292 // Returns a MessageLoopProxy instance corresponding to the message loop
293 // of the thread on which media operations should be run. Must be called
294 // on the renderer's main thread.
295 scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
297 // Causes the idle handler to skip sending idle notifications
298 // on the two next scheduled calls, so idle notifications are
299 // not sent for at least one notification delay.
300 void PostponeIdleNotification();
302 scoped_refptr<media::GpuVideoAcceleratorFactories> GetGpuFactories();
304 scoped_refptr<webkit::gpu::ContextProviderWebContext>
305 SharedMainThreadContextProvider();
307 // AudioRendererMixerManager instance which manages renderer side mixer
308 // instances shared based on configured audio parameters. Lazily created on
309 // first call.
310 AudioRendererMixerManager* GetAudioRendererMixerManager();
312 // AudioHardwareConfig contains audio hardware configuration for
313 // renderer side clients. Creation requires a synchronous IPC call so it is
314 // lazily created on the first call.
315 media::AudioHardwareConfig* GetAudioHardwareConfig();
317 #if defined(OS_WIN)
318 void PreCacheFontCharacters(const LOGFONT& log_font,
319 const base::string16& str);
320 #endif
322 #if defined(ENABLE_WEBRTC)
323 WebRTCIdentityService* get_webrtc_identity_service() {
324 return webrtc_identity_service_.get();
326 #endif
328 // For producing custom V8 histograms. Custom histograms are produced if all
329 // RenderViews share the same host, and the host is in the pre-specified set
330 // of hosts we want to produce custom diagrams for. The name for a custom
331 // diagram is the name of the corresponding generic diagram plus a
332 // host-specific suffix.
333 class CONTENT_EXPORT HistogramCustomizer {
334 public:
335 HistogramCustomizer();
336 ~HistogramCustomizer();
338 // Called when a top frame of a RenderView navigates. This function updates
339 // RenderThreadImpl's information about whether all RenderViews are
340 // displaying a page from the same host. |host| is the host where a
341 // RenderView navigated, and |view_count| is the number of RenderViews in
342 // this process.
343 void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
345 // Used for customizing some histograms if all RenderViews share the same
346 // host. Returns the current custom histogram name to use for
347 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
348 std::string ConvertToCustomHistogramName(const char* histogram_name) const;
350 private:
351 friend class RenderThreadImplUnittest;
353 // Used for updating the information on which is the common host which all
354 // RenderView's share (if any). If there is no common host, this function is
355 // called with an empty string.
356 void SetCommonHost(const std::string& host);
358 // The current common host of the RenderViews; empty string if there is no
359 // common host.
360 std::string common_host_;
361 // The corresponding suffix.
362 std::string common_host_histogram_suffix_;
363 // Set of histograms for which we want to produce a custom histogram if
364 // possible.
365 std::set<std::string> custom_histograms_;
367 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
370 HistogramCustomizer* histogram_customizer() {
371 return &histogram_customizer_;
374 void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
375 const std::vector<float>& new_touchscreen);
377 // Retrieve current gamepad data.
378 void SampleGamepads(blink::WebGamepads* data);
380 // Set a listener for gamepad connected/disconnected events.
381 // A non-null listener must be set first before calling SampleGamepads.
382 void SetGamepadListener(blink::WebGamepadListener* listener);
384 // Called by a RenderWidget when it is created or destroyed. This
385 // allows the process to know when there are no visible widgets.
386 void WidgetCreated();
387 void WidgetDestroyed();
388 void WidgetHidden();
389 void WidgetRestored();
391 void AddEmbeddedWorkerRoute(int32 routing_id, IPC::Listener* listener);
392 void RemoveEmbeddedWorkerRoute(int32 routing_id);
394 private:
395 // ChildThread
396 virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
398 // GpuChannelHostFactory implementation:
399 virtual bool IsMainThread() OVERRIDE;
400 virtual base::MessageLoop* GetMainLoop() OVERRIDE;
401 virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
402 virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
403 size_t size) OVERRIDE;
404 virtual bool CreateViewCommandBuffer(
405 int32 surface_id,
406 const GPUCreateCommandBufferConfig& init_params,
407 int32 route_id) OVERRIDE;
408 virtual void CreateImage(
409 gfx::PluginWindowHandle window,
410 int32 image_id,
411 const CreateImageCallback& callback) OVERRIDE;
412 virtual void DeleteImage(int32 image_id, int32 sync_point) OVERRIDE;
413 virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
414 size_t width,
415 size_t height,
416 unsigned internalformat,
417 unsigned usage) OVERRIDE;
419 // mojo::ServiceProvider implementation:
420 virtual void ConnectToService(
421 const mojo::String& service_name,
422 mojo::ScopedMessagePipeHandle message_pipe) OVERRIDE;
424 void Init();
426 void OnSetZoomLevelForCurrentURL(const std::string& scheme,
427 const std::string& host,
428 double zoom_level);
429 void OnCreateNewView(const ViewMsg_New_Params& params);
430 void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
431 void OnPurgePluginListCache(bool reload_pages);
432 void OnNetworkStateChanged(bool online);
433 void OnGetAccessibilityTree();
434 void OnTempCrashWithData(const GURL& data);
435 void OnUpdateTimezone();
436 void OnMemoryPressure(
437 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
438 #if defined(OS_ANDROID)
439 void OnSetWebKitSharedTimersSuspended(bool suspend);
440 #endif
441 #if defined(OS_MACOSX)
442 void OnUpdateScrollbarTheme(float initial_button_delay,
443 float autoscroll_button_delay,
444 bool jump_on_track_click,
445 blink::ScrollerStyle preferred_scroller_style,
446 bool redraw);
447 #endif
448 void OnCreateNewSharedWorker(
449 const WorkerProcessMsg_CreateWorker_Params& params);
451 void IdleHandlerInForegroundTab();
453 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
455 // These objects live solely on the render thread.
456 scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
457 scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
458 scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
459 scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
460 scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
462 // Used on the render thread and deleted by WebKit at shutdown.
463 blink::WebMediaStreamCenter* media_stream_center_;
465 // Used on the renderer and IPC threads.
466 scoped_refptr<DBMessageFilter> db_message_filter_;
467 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
468 scoped_refptr<AudioMessageFilter> audio_message_filter_;
469 scoped_refptr<MidiMessageFilter> midi_message_filter_;
470 #if defined(OS_ANDROID)
471 scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
472 #endif
473 scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
475 scoped_ptr<PeerConnectionDependencyFactory> peer_connection_factory_;
477 // This is used to communicate to the browser process the status
478 // of all the peer connections created in the renderer.
479 scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
481 // Dispatches all P2P sockets.
482 scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
484 // Used on the render thread.
485 scoped_ptr<VideoCaptureImplManager> vc_manager_;
487 // The count of RenderWidgets running through this thread.
488 int widget_count_;
490 // The count of hidden RenderWidgets running through this thread.
491 int hidden_widget_count_;
493 // The current value of the idle notification timer delay.
494 int64 idle_notification_delay_in_ms_;
496 // The number of idle handler calls that skip sending idle notifications.
497 int idle_notifications_to_skip_;
499 bool suspend_webkit_shared_timer_;
500 bool notify_webkit_of_modal_loop_;
501 bool webkit_shared_timer_suspended_;
503 // The following flag is used to control layout test specific behavior.
504 bool layout_test_mode_;
506 // Timer that periodically calls IdleHandler.
507 base::RepeatingTimer<RenderThreadImpl> idle_timer_;
509 // The channel from the renderer process to the GPU process.
510 scoped_refptr<GpuChannelHost> gpu_channel_;
512 // Cache of variables that are needed on the compositor thread by
513 // GpuChannelHostFactory methods.
514 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
516 // A lazily initiated thread on which file operations are run.
517 scoped_ptr<base::Thread> file_thread_;
519 // May be null if overridden by ContentRendererClient.
520 scoped_ptr<base::Thread> compositor_thread_;
522 // Thread for running multimedia operations (e.g., video decoding).
523 scoped_ptr<base::Thread> media_thread_;
525 // Will point to appropriate MessageLoopProxy after initialization,
526 // regardless of whether |compositor_thread_| is overriden.
527 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
529 // May be null if unused by the |input_handler_manager_|.
530 scoped_refptr<InputEventFilter> input_event_filter_;
531 scoped_ptr<InputHandlerManager> input_handler_manager_;
532 scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
534 scoped_refptr<ContextProviderCommandBuffer> shared_main_thread_contexts_;
536 ObserverList<RenderProcessObserver> observers_;
538 scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
540 scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
541 scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
543 HistogramCustomizer histogram_customizer_;
545 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
547 scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
549 scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
551 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
552 // multiple threads. Current allocation mechanism for IOSurface
553 // backed GpuMemoryBuffers prevent this. crbug.com/325045
554 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_;
556 // Compositor settings
557 bool is_gpu_rasterization_enabled_;
558 bool is_gpu_rasterization_forced_;
559 bool is_impl_side_painting_enabled_;
560 bool is_low_res_tiling_enabled_;
561 bool is_lcd_text_enabled_;
562 bool is_distance_field_text_enabled_;
563 bool is_zero_copy_enabled_;
564 bool is_one_copy_enabled_;
566 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
569 } // namespace content
571 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_