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