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