c05d775f60e43906fe54614e12334754aaa8d4e5
[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/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"
26
27 #if defined(OS_MACOSX)
28 #include "third_party/WebKit/public/web/mac/WebScrollbarTheme.h"
29 #endif
30
31 class GrContext;
32 class SkBitmap;
33 struct ViewMsg_New_Params;
34
35 namespace blink {
36 class WebGamepads;
37 class WebGraphicsContext3D;
38 class WebMediaStreamCenter;
39 class WebMediaStreamCenterClient;
40 }
41
42 namespace base {
43 class MessageLoopProxy;
44 class Thread;
45 }
46
47 namespace cc {
48 class ContextProvider;
49 }
50
51 namespace IPC {
52 class ForwardingMessageFilter;
53 }
54
55 namespace media {
56 class AudioHardwareConfig;
57 }
58
59 namespace v8 {
60 class Extension;
61 }
62
63 namespace webkit {
64 namespace gpu {
65 class ContextProviderWebContext;
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 EmbeddedWorkerDispatcher;
81 class GamepadSharedMemoryReader;
82 class GpuChannelHost;
83 class IndexedDBDispatcher;
84 class InputEventFilter;
85 class InputHandlerManager;
86 class MediaStreamCenter;
87 class MediaStreamDependencyFactory;
88 class MIDIMessageFilter;
89 class P2PSocketDispatcher;
90 class PeerConnectionTracker;
91 class RendererDemuxerAndroid;
92 class RendererWebKitPlatformSupportImpl;
93 class RenderProcessObserver;
94 class VideoCaptureImplManager;
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 EnsureWebKitInitialized() OVERRIDE;
141   virtual void RecordAction(const base::UserMetricsAction& action) OVERRIDE;
142   virtual void RecordComputedAction(const std::string& action) OVERRIDE;
143   virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
144       size_t buffer_size) OVERRIDE;
145   virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
146   virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
147   virtual void IdleHandler() OVERRIDE;
148   virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
149   virtual void SetIdleNotificationDelayInMs(
150       int64 idle_notification_delay_in_ms) OVERRIDE;
151   virtual void UpdateHistograms(int sequence_number) OVERRIDE;
152   virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
153   virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
154 #if defined(OS_WIN)
155   virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
156   virtual void ReleaseCachedFonts() OVERRIDE;
157 #endif
158
159   // Synchronously establish a channel to the GPU plugin if not previously
160   // established or if it has been lost (for example if the GPU plugin crashed).
161   // If there is a pending asynchronous request, it will be completed by the
162   // time this routine returns.
163   GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
164
165
166   // These methods modify how the next message is sent.  Normally, when sending
167   // a synchronous message that runs a nested message loop, we need to suspend
168   // callbacks into WebKit.  This involves disabling timers and deferring
169   // resource loads.  However, there are exceptions when we need to customize
170   // the behavior.
171   void DoNotSuspendWebKitSharedTimer();
172   void DoNotNotifyWebKitOfModalLoop();
173
174   // True if we are running layout tests. This currently disables forwarding
175   // various status messages to the console, skips network error pages, and
176   // short circuits size update and focus events.
177   bool layout_test_mode() const {
178     return layout_test_mode_;
179   }
180   void set_layout_test_mode(bool layout_test_mode) {
181     layout_test_mode_ = layout_test_mode;
182   }
183
184   IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
185     return compositor_output_surface_filter_.get();
186   }
187
188   InputHandlerManager* input_handler_manager() const {
189     return input_handler_manager_.get();
190   }
191
192   // Will be NULL if threaded compositing has not been enabled.
193   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
194     return compositor_message_loop_proxy_;
195   }
196
197   AppCacheDispatcher* appcache_dispatcher() const {
198     return appcache_dispatcher_.get();
199   }
200
201   DomStorageDispatcher* dom_storage_dispatcher() const {
202     return dom_storage_dispatcher_.get();
203   }
204
205   EmbeddedWorkerDispatcher* embedded_worker_dispatcher() const {
206     return embedded_worker_dispatcher_.get();
207   }
208
209   AudioInputMessageFilter* audio_input_message_filter() {
210     return audio_input_message_filter_.get();
211   }
212
213   AudioMessageFilter* audio_message_filter() {
214     return audio_message_filter_.get();
215   }
216
217   MIDIMessageFilter* midi_message_filter() {
218     return midi_message_filter_.get();
219   }
220
221 #if defined(OS_ANDROID)
222   RendererDemuxerAndroid* renderer_demuxer() {
223     return renderer_demuxer_.get();
224   }
225 #endif
226
227   // Creates the embedder implementation of WebMediaStreamCenter.
228   // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
229   blink::WebMediaStreamCenter* CreateMediaStreamCenter(
230       blink::WebMediaStreamCenterClient* client);
231
232   // Returns a factory used for creating RTC PeerConnection objects.
233   MediaStreamDependencyFactory* GetMediaStreamDependencyFactory();
234
235   PeerConnectionTracker* peer_connection_tracker() {
236     return peer_connection_tracker_.get();
237   }
238
239   // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
240   P2PSocketDispatcher* p2p_socket_dispatcher() {
241     return p2p_socket_dispatcher_.get();
242   }
243
244   VideoCaptureImplManager* video_capture_impl_manager() const {
245     return vc_manager_.get();
246   }
247
248   // Get the GPU channel. Returns NULL if the channel is not established or
249   // has been lost.
250   GpuChannelHost* GetGpuChannel();
251
252   // Returns a MessageLoopProxy instance corresponding to the message loop
253   // of the thread on which file operations should be run. Must be called
254   // on the renderer's main thread.
255   scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
256
257   // Returns a MessageLoopProxy instance corresponding to the message loop
258   // of the thread on which media operations should be run. Must be called
259   // on the renderer's main thread.
260   scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
261
262   // Causes the idle handler to skip sending idle notifications
263   // on the two next scheduled calls, so idle notifications are
264   // not sent for at least one notification delay.
265   void PostponeIdleNotification();
266
267   scoped_refptr<RendererGpuVideoAcceleratorFactories> GetGpuFactories();
268
269   scoped_refptr<cc::ContextProvider> OffscreenCompositorContextProvider();
270   scoped_refptr<webkit::gpu::ContextProviderWebContext>
271       SharedMainThreadContextProvider();
272
273   // AudioRendererMixerManager instance which manages renderer side mixer
274   // instances shared based on configured audio parameters.  Lazily created on
275   // first call.
276   AudioRendererMixerManager* GetAudioRendererMixerManager();
277
278   // AudioHardwareConfig contains audio hardware configuration for
279   // renderer side clients.  Creation requires a synchronous IPC call so it is
280   // lazily created on the first call.
281   media::AudioHardwareConfig* GetAudioHardwareConfig();
282
283 #if defined(OS_WIN)
284   void PreCacheFontCharacters(const LOGFONT& log_font,
285                               const base::string16& str);
286 #endif
287
288 #if defined(ENABLE_WEBRTC)
289   WebRTCIdentityService* get_webrtc_identity_service() {
290     return webrtc_identity_service_.get();
291   }
292 #endif
293
294   // For producing custom V8 histograms. Custom histograms are produced if all
295   // RenderViews share the same host, and the host is in the pre-specified set
296   // of hosts we want to produce custom diagrams for. The name for a custom
297   // diagram is the name of the corresponding generic diagram plus a
298   // host-specific suffix.
299   class CONTENT_EXPORT HistogramCustomizer {
300    public:
301     HistogramCustomizer();
302     ~HistogramCustomizer();
303
304     // Called when a top frame of a RenderView navigates. This function updates
305     // RenderThreadImpl's information about whether all RenderViews are
306     // displaying a page from the same host. |host| is the host where a
307     // RenderView navigated, and |view_count| is the number of RenderViews in
308     // this process.
309     void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
310
311     // Used for customizing some histograms if all RenderViews share the same
312     // host. Returns the current custom histogram name to use for
313     // |histogram_name|, or |histogram_name| if it shouldn't be customized.
314     std::string ConvertToCustomHistogramName(const char* histogram_name) const;
315
316    private:
317     friend class RenderThreadImplUnittest;
318
319     // Used for updating the information on which is the common host which all
320     // RenderView's share (if any). If there is no common host, this function is
321     // called with an empty string.
322     void SetCommonHost(const std::string& host);
323
324     // The current common host of the RenderViews; empty string if there is no
325     // common host.
326     std::string common_host_;
327     // The corresponding suffix.
328     std::string common_host_histogram_suffix_;
329     // Set of histograms for which we want to produce a custom histogram if
330     // possible.
331     std::set<std::string> custom_histograms_;
332
333     DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
334   };
335
336   HistogramCustomizer* histogram_customizer() {
337     return &histogram_customizer_;
338   }
339
340   void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
341                                const std::vector<float>& new_touchscreen);
342
343   // Retrieve current gamepad data.
344   void SampleGamepads(blink::WebGamepads* data);
345
346   // Called by a RenderWidget when it is created or destroyed. This
347   // allows the process to know when there are no visible widgets.
348   void WidgetCreated();
349   void WidgetDestroyed();
350   void WidgetHidden();
351   void WidgetRestored();
352
353  private:
354   // ChildThread
355   virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
356
357   // GpuChannelHostFactory implementation:
358   virtual bool IsMainThread() OVERRIDE;
359   virtual base::MessageLoop* GetMainLoop() OVERRIDE;
360   virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
361   virtual base::WaitableEvent* GetShutDownEvent() OVERRIDE;
362   virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
363       size_t size) OVERRIDE;
364   virtual int32 CreateViewCommandBuffer(
365       int32 surface_id,
366       const GPUCreateCommandBufferConfig& init_params) OVERRIDE;
367   virtual void CreateImage(
368       gfx::PluginWindowHandle window,
369       int32 image_id,
370       const CreateImageCallback& callback) OVERRIDE;
371   virtual void DeleteImage(int32 image_id, int32 sync_point) OVERRIDE;
372   virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
373       size_t width,
374       size_t height,
375       unsigned internalformat) OVERRIDE;
376
377   void Init();
378
379   void OnSetZoomLevelForCurrentURL(const std::string& scheme,
380                                    const std::string& host,
381                                    double zoom_level);
382   void OnCreateNewView(const ViewMsg_New_Params& params);
383   void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
384   void OnPurgePluginListCache(bool reload_pages);
385   void OnNetworkStateChanged(bool online);
386   void OnGetAccessibilityTree();
387   void OnTempCrashWithData(const GURL& data);
388   void OnMemoryPressure(
389       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
390 #if defined(OS_ANDROID)
391   void OnSetWebKitSharedTimersSuspended(bool suspend);
392 #endif
393 #if defined(OS_MACOSX)
394   void OnUpdateScrollbarTheme(float initial_button_delay,
395                               float autoscroll_button_delay,
396                               bool jump_on_track_click,
397                               blink::ScrollerStyle preferred_scroller_style,
398                               bool redraw);
399 #endif
400
401   void IdleHandlerInForegroundTab();
402
403   scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
404
405   // These objects live solely on the render thread.
406   scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
407   scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
408   scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
409   scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
410   scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
411
412   // Used on the render thread and deleted by WebKit at shutdown.
413   blink::WebMediaStreamCenter* media_stream_center_;
414
415   // Used on the renderer and IPC threads.
416   scoped_refptr<DBMessageFilter> db_message_filter_;
417   scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
418   scoped_refptr<AudioMessageFilter> audio_message_filter_;
419   scoped_refptr<MIDIMessageFilter> midi_message_filter_;
420 #if defined(OS_ANDROID)
421   scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
422 #endif
423   scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
424
425   scoped_ptr<MediaStreamDependencyFactory> media_stream_factory_;
426
427   // This is used to communicate to the browser process the status
428   // of all the peer connections created in the renderer.
429   scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
430
431   // Dispatches all P2P sockets.
432   scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
433
434   // Used on the render thread.
435   scoped_ptr<VideoCaptureImplManager> vc_manager_;
436
437   // The count of RenderWidgets running through this thread.
438   int widget_count_;
439
440   // The count of hidden RenderWidgets running through this thread.
441   int hidden_widget_count_;
442
443   // The current value of the idle notification timer delay.
444   int64 idle_notification_delay_in_ms_;
445
446   // The number of idle handler calls that skip sending idle notifications.
447   int idle_notifications_to_skip_;
448
449   bool suspend_webkit_shared_timer_;
450   bool notify_webkit_of_modal_loop_;
451   bool webkit_shared_timer_suspended_;
452
453   // The following flag is used to control layout test specific behavior.
454   bool layout_test_mode_;
455
456   // Timer that periodically calls IdleHandler.
457   base::RepeatingTimer<RenderThreadImpl> idle_timer_;
458
459   // The channel from the renderer process to the GPU process.
460   scoped_refptr<GpuChannelHost> gpu_channel_;
461
462   // Cache of variables that are needed on the compositor thread by
463   // GpuChannelHostFactory methods.
464   scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
465   base::WaitableEvent* shutdown_event_;
466
467   // A lazily initiated thread on which file operations are run.
468   scoped_ptr<base::Thread> file_thread_;
469
470   // May be null if overridden by ContentRendererClient.
471   scoped_ptr<base::Thread> compositor_thread_;
472
473   // Thread for running multimedia operations (e.g., video decoding).
474   scoped_ptr<base::Thread> media_thread_;
475
476   // Will point to appropriate MessageLoopProxy after initialization,
477   // regardless of whether |compositor_thread_| is overriden.
478   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
479
480   // May be null if unused by the |input_handler_manager_|.
481   scoped_refptr<InputEventFilter> input_event_filter_;
482   scoped_ptr<InputHandlerManager> input_handler_manager_;
483   scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
484
485   scoped_refptr<ContextProviderCommandBuffer> offscreen_compositor_contexts_;
486   scoped_refptr<ContextProviderCommandBuffer> shared_main_thread_contexts_;
487
488   ObserverList<RenderProcessObserver> observers_;
489
490   scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
491
492   scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
493   scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
494
495   HistogramCustomizer histogram_customizer_;
496
497   scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
498
499   scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
500
501   scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
502
503   // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
504   // multiple threads. Current allocation mechanism for IOSurface
505   // backed GpuMemoryBuffers prevent this. crbug.com/325045
506   base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_;
507
508   DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
509 };
510
511 }  // namespace content
512
513 #endif  // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_