- add sources.
[platform/framework/web/crosswalk.git] / src / content / renderer / render_thread_impl.h
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.
4
5 #ifndef CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
6 #define CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
7
8 #include <set>
9 #include <string>
10 #include <vector>
11
12 #include "base/memory/memory_pressure_listener.h"
13 #include "base/observer_list.h"
14 #include "base/process/process_handle.h"
15 #include "base/strings/string16.h"
16 #include "base/timer/timer.h"
17 #include "build/build_config.h"
18 #include "content/child/child_thread.h"
19 #include "content/common/content_export.h"
20 #include "content/common/gpu/client/gpu_channel_host.h"
21 #include "content/public/renderer/render_thread.h"
22 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
23 #include "ipc/ipc_channel_proxy.h"
24 #include "ui/gfx/native_widget_types.h"
25
26 class GrContext;
27 class SkBitmap;
28 struct ViewMsg_New_Params;
29
30 namespace WebKit {
31 class WebGamepads;
32 class WebGraphicsContext3D;
33 class WebMediaStreamCenter;
34 class WebMediaStreamCenterClient;
35 }
36
37 namespace base {
38 class MessageLoopProxy;
39 class Thread;
40
41 #if defined(OS_WIN)
42 namespace win {
43 class ScopedCOMInitializer;
44 }
45 #endif
46 }
47
48 namespace cc {
49 class ContextProvider;
50 }
51
52 namespace IPC {
53 class ForwardingMessageFilter;
54 }
55
56 namespace media {
57 class AudioHardwareConfig;
58 }
59
60 namespace v8 {
61 class Extension;
62 }
63
64 namespace webkit {
65 namespace gpu {
66 class GrContextForWebGraphicsContext3D;
67 }
68 }
69
70 namespace content {
71
72 class AppCacheDispatcher;
73 class AudioInputMessageFilter;
74 class AudioMessageFilter;
75 class AudioRendererMixerManager;
76 class ContextProviderCommandBuffer;
77 class DBMessageFilter;
78 class DevToolsAgentFilter;
79 class DomStorageDispatcher;
80 class GamepadSharedMemoryReader;
81 class GpuChannelHost;
82 class IndexedDBDispatcher;
83 class InputEventFilter;
84 class InputHandlerManager;
85 class MediaStreamCenter;
86 class MediaStreamDependencyFactory;
87 class MIDIMessageFilter;
88 class P2PSocketDispatcher;
89 class PeerConnectionTracker;
90 class RendererDemuxerAndroid;
91 class RendererWebKitPlatformSupportImpl;
92 class RenderProcessObserver;
93 class VideoCaptureImplManager;
94 class WebDatabaseObserverImpl;
95 class WebGraphicsContext3DCommandBufferImpl;
96 class WebRTCIdentityService;
97
98 // The RenderThreadImpl class represents a background thread where RenderView
99 // instances live.  The RenderThread supports an API that is used by its
100 // consumer to talk indirectly to the RenderViews and supporting objects.
101 // Likewise, it provides an API for the RenderViews to talk back to the main
102 // process (i.e., their corresponding WebContentsImpl).
103 //
104 // Most of the communication occurs in the form of IPC messages.  They are
105 // routed to the RenderThread according to the routing IDs of the messages.
106 // The routing IDs correspond to RenderView instances.
107 class CONTENT_EXPORT RenderThreadImpl : public RenderThread,
108                                         public ChildThread,
109                                         public GpuChannelHostFactory {
110  public:
111   static RenderThreadImpl* current();
112
113   RenderThreadImpl();
114   // Constructor that's used when running in single process mode.
115   explicit RenderThreadImpl(const std::string& channel_name);
116   virtual ~RenderThreadImpl();
117   virtual void Shutdown() OVERRIDE;
118
119   // When initializing WebKit, ensure that any schemes needed for the content
120   // module are registered properly.  Static to allow sharing with tests.
121   static void RegisterSchemes();
122
123   // RenderThread implementation:
124   virtual bool Send(IPC::Message* msg) OVERRIDE;
125   virtual base::MessageLoop* GetMessageLoop() OVERRIDE;
126   virtual IPC::SyncChannel* GetChannel() OVERRIDE;
127   virtual std::string GetLocale() OVERRIDE;
128   virtual IPC::SyncMessageFilter* GetSyncMessageFilter() OVERRIDE;
129   virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy()
130       OVERRIDE;
131   virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
132   virtual void RemoveRoute(int32 routing_id) OVERRIDE;
133   virtual int GenerateRoutingID() OVERRIDE;
134   virtual void AddFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
135   virtual void RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
136   virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
137   virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
138   virtual void SetResourceDispatcherDelegate(
139       ResourceDispatcherDelegate* delegate) OVERRIDE;
140   virtual void WidgetHidden() OVERRIDE;
141   virtual void WidgetRestored() OVERRIDE;
142   virtual void EnsureWebKitInitialized() OVERRIDE;
143   virtual void RecordUserMetrics(const std::string& action) OVERRIDE;
144   virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
145       size_t buffer_size) OVERRIDE;
146   virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
147   virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
148   virtual void IdleHandler() OVERRIDE;
149   virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
150   virtual void SetIdleNotificationDelayInMs(
151       int64 idle_notification_delay_in_ms) OVERRIDE;
152   virtual void ToggleWebKitSharedTimer(bool suspend) OVERRIDE;
153   virtual void UpdateHistograms(int sequence_number) OVERRIDE;
154   virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
155   virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
156 #if defined(OS_WIN)
157   virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
158   virtual void ReleaseCachedFonts() OVERRIDE;
159 #endif
160
161   // Synchronously establish a channel to the GPU plugin if not previously
162   // established or if it has been lost (for example if the GPU plugin crashed).
163   // If there is a pending asynchronous request, it will be completed by the
164   // time this routine returns.
165   GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
166
167
168   // These methods modify how the next message is sent.  Normally, when sending
169   // a synchronous message that runs a nested message loop, we need to suspend
170   // callbacks into WebKit.  This involves disabling timers and deferring
171   // resource loads.  However, there are exceptions when we need to customize
172   // the behavior.
173   void DoNotSuspendWebKitSharedTimer();
174   void DoNotNotifyWebKitOfModalLoop();
175
176   // True if we are running layout tests. This currently disables forwarding
177   // various status messages to the console, skips network error pages, and
178   // short circuits size update and focus events.
179   bool layout_test_mode() const {
180     return layout_test_mode_;
181   }
182   void set_layout_test_mode(bool layout_test_mode) {
183     layout_test_mode_ = layout_test_mode;
184   }
185
186   IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
187     return compositor_output_surface_filter_.get();
188   }
189
190   InputHandlerManager* input_handler_manager() const {
191     return input_handler_manager_.get();
192   }
193
194   // Will be NULL if threaded compositing has not been enabled.
195   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
196     return compositor_message_loop_proxy_;
197   }
198
199   AppCacheDispatcher* appcache_dispatcher() const {
200     return appcache_dispatcher_.get();
201   }
202
203   DomStorageDispatcher* dom_storage_dispatcher() const {
204     return dom_storage_dispatcher_.get();
205   }
206
207   AudioInputMessageFilter* audio_input_message_filter() {
208     return audio_input_message_filter_.get();
209   }
210
211   AudioMessageFilter* audio_message_filter() {
212     return audio_message_filter_.get();
213   }
214
215   MIDIMessageFilter* midi_message_filter() {
216     return midi_message_filter_.get();
217   }
218
219 #if defined(OS_ANDROID)
220   RendererDemuxerAndroid* renderer_demuxer() {
221     return renderer_demuxer_.get();
222   }
223 #endif
224
225   // Creates the embedder implementation of WebMediaStreamCenter.
226   // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
227   WebKit::WebMediaStreamCenter* CreateMediaStreamCenter(
228       WebKit::WebMediaStreamCenterClient* client);
229
230   // Returns a factory used for creating RTC PeerConnection objects.
231   MediaStreamDependencyFactory* GetMediaStreamDependencyFactory();
232
233   PeerConnectionTracker* peer_connection_tracker() {
234     return peer_connection_tracker_.get();
235   }
236
237   // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
238   P2PSocketDispatcher* p2p_socket_dispatcher() {
239     return p2p_socket_dispatcher_.get();
240   }
241
242   VideoCaptureImplManager* video_capture_impl_manager() const {
243     return vc_manager_.get();
244   }
245
246   // Get the GPU channel. Returns NULL if the channel is not established or
247   // has been lost.
248   GpuChannelHost* GetGpuChannel();
249
250   // Returns a MessageLoopProxy instance corresponding to the message loop
251   // of the thread on which file operations should be run. Must be called
252   // on the renderer's main thread.
253   scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
254
255   // Returns a MessageLoopProxy instance corresponding to the message loop
256   // of the thread on which media operations should be run. Must be called
257   // on the renderer's main thread.
258   scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
259
260   // Causes the idle handler to skip sending idle notifications
261   // on the two next scheduled calls, so idle notifications are
262   // not sent for at least one notification delay.
263   void PostponeIdleNotification();
264
265   scoped_refptr<RendererGpuVideoAcceleratorFactories> GetGpuFactories();
266
267   scoped_refptr<cc::ContextProvider> OffscreenCompositorContextProvider();
268   scoped_refptr<cc::ContextProvider> SharedMainThreadContextProvider();
269
270   // AudioRendererMixerManager instance which manages renderer side mixer
271   // instances shared based on configured audio parameters.  Lazily created on
272   // first call.
273   AudioRendererMixerManager* GetAudioRendererMixerManager();
274
275   // AudioHardwareConfig contains audio hardware configuration for
276   // renderer side clients.  Creation requires a synchronous IPC call so it is
277   // lazily created on the first call.
278   media::AudioHardwareConfig* GetAudioHardwareConfig();
279
280 #if defined(OS_WIN)
281   void PreCacheFontCharacters(const LOGFONT& log_font, const string16& str);
282 #endif
283
284 #if defined(ENABLE_WEBRTC)
285   WebRTCIdentityService* get_webrtc_identity_service() {
286     return webrtc_identity_service_.get();
287   }
288 #endif
289
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();
299
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);
306
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;
311
312    private:
313     friend class RenderThreadImplUnittest;
314
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);
319
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_;
328
329     DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
330   };
331
332   HistogramCustomizer* histogram_customizer() {
333     return &histogram_customizer_;
334   }
335
336   void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
337                                const std::vector<float>& new_touchscreen);
338
339   // Retrieve current gamepad data.
340   void SampleGamepads(WebKit::WebGamepads* data);
341
342   // Get the browser process's notion of the renderer process's ID.
343   // This is the first argument to RenderWidgetHost::FromID. Ideally
344   // this would be available on all platforms via base::Process.
345   base::ProcessId renderer_process_id() const;
346
347  private:
348   // ChildThread
349   virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
350
351   // GpuChannelHostFactory implementation:
352   virtual bool IsMainThread() OVERRIDE;
353   virtual base::MessageLoop* GetMainLoop() OVERRIDE;
354   virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
355   virtual base::WaitableEvent* GetShutDownEvent() OVERRIDE;
356   virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
357       size_t size) OVERRIDE;
358   virtual int32 CreateViewCommandBuffer(
359       int32 surface_id,
360       const GPUCreateCommandBufferConfig& init_params) OVERRIDE;
361   virtual void CreateImage(
362       gfx::PluginWindowHandle window,
363       int32 image_id,
364       const CreateImageCallback& callback) OVERRIDE;
365   virtual void DeleteImage(int32 image_id, int32 sync_point) OVERRIDE;
366   virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
367       size_t width,
368       size_t height,
369       unsigned internalformat) OVERRIDE;
370
371   void Init();
372
373   void OnSetZoomLevelForCurrentURL(const std::string& scheme,
374                                    const std::string& host,
375                                    double zoom_level);
376   void OnCreateNewView(const ViewMsg_New_Params& params);
377   void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
378   void OnPurgePluginListCache(bool reload_pages);
379   void OnNetworkStateChanged(bool online);
380   void OnGetAccessibilityTree();
381   void OnTempCrashWithData(const GURL& data);
382   void OnSetRendererProcessID(base::ProcessId process_id);
383   void OnSetWebKitSharedTimersSuspended(bool suspend);
384   void OnMemoryPressure(
385       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
386
387   void IdleHandlerInForegroundTab();
388
389   scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
390
391   // These objects live solely on the render thread.
392   scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
393   scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
394   scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
395   scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
396
397   // Used on the render thread and deleted by WebKit at shutdown.
398   WebKit::WebMediaStreamCenter* media_stream_center_;
399
400   // Used on the renderer and IPC threads.
401   scoped_refptr<DBMessageFilter> db_message_filter_;
402   scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
403   scoped_refptr<AudioMessageFilter> audio_message_filter_;
404   scoped_refptr<MIDIMessageFilter> midi_message_filter_;
405 #if defined(OS_ANDROID)
406   scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
407 #endif
408   scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
409
410   scoped_ptr<MediaStreamDependencyFactory> media_stream_factory_;
411
412   // This is used to communicate to the browser process the status
413   // of all the peer connections created in the renderer.
414   scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
415
416   // Dispatches all P2P sockets.
417   scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
418
419   // Used on multiple threads.
420   scoped_refptr<VideoCaptureImplManager> vc_manager_;
421
422   // Used on multiple script execution context threads.
423   scoped_ptr<WebDatabaseObserverImpl> web_database_observer_impl_;
424
425 #if defined(OS_WIN)
426   // Initialize COM when using plugins outside the sandbox.
427   scoped_ptr<base::win::ScopedCOMInitializer> initialize_com_;
428 #endif
429
430   // The count of RenderWidgets running through this thread.
431   int widget_count_;
432
433   // The count of hidden RenderWidgets running through this thread.
434   int hidden_widget_count_;
435
436   // The current value of the idle notification timer delay.
437   int64 idle_notification_delay_in_ms_;
438
439   // The number of idle handler calls that skip sending idle notifications.
440   int idle_notifications_to_skip_;
441
442   bool suspend_webkit_shared_timer_;
443   bool notify_webkit_of_modal_loop_;
444
445   // The following flag is used to control layout test specific behavior.
446   bool layout_test_mode_;
447
448   // Timer that periodically calls IdleHandler.
449   base::RepeatingTimer<RenderThreadImpl> idle_timer_;
450
451   // The channel from the renderer process to the GPU process.
452   scoped_refptr<GpuChannelHost> gpu_channel_;
453
454   // Cache of variables that are needed on the compositor thread by
455   // GpuChannelHostFactory methods.
456   scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
457   base::WaitableEvent* shutdown_event_;
458
459   // A lazily initiated thread on which file operations are run.
460   scoped_ptr<base::Thread> file_thread_;
461
462   // May be null if overridden by ContentRendererClient.
463   scoped_ptr<base::Thread> compositor_thread_;
464
465   // Thread for running multimedia operations (e.g., video decoding).
466   scoped_ptr<base::Thread> media_thread_;
467
468   // Will point to appropriate MessageLoopProxy after initialization,
469   // regardless of whether |compositor_thread_| is overriden.
470   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
471
472   // May be null if unused by the |input_handler_manager_|.
473   scoped_refptr<InputEventFilter> input_event_filter_;
474   scoped_ptr<InputHandlerManager> input_handler_manager_;
475   scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
476
477   scoped_refptr<ContextProviderCommandBuffer> offscreen_compositor_contexts_;
478   scoped_refptr<ContextProviderCommandBuffer> shared_main_thread_contexts_;
479
480   ObserverList<RenderProcessObserver> observers_;
481
482   scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
483
484   scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
485   scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
486
487   HistogramCustomizer histogram_customizer_;
488
489   scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
490
491   scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
492
493   scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
494
495   base::ProcessId renderer_process_id_;
496
497   DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
498 };
499
500 }  // namespace content
501
502 #endif  // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_