Home | History | Annotate | Download | only in renderer
      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/strings/string16.h"
     15 #include "base/timer/timer.h"
     16 #include "build/build_config.h"
     17 #include "content/child/child_thread.h"
     18 #include "content/common/content_export.h"
     19 #include "content/common/gpu/client/gpu_channel_host.h"
     20 #include "content/common/gpu/gpu_process_launch_causes.h"
     21 #include "content/public/renderer/render_thread.h"
     22 #include "content/renderer/media/renderer_gpu_video_decoder_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 class GpuVideoDecoderFactories;
     59 }
     60 
     61 namespace v8 {
     62 class Extension;
     63 }
     64 
     65 namespace webkit {
     66 namespace gpu {
     67 class GrContextForWebGraphicsContext3D;
     68 }
     69 }
     70 
     71 namespace content {
     72 
     73 class AppCacheDispatcher;
     74 class AudioInputMessageFilter;
     75 class AudioMessageFilter;
     76 class AudioRendererMixerManager;
     77 class ContextProviderCommandBuffer;
     78 class DBMessageFilter;
     79 class DevToolsAgentFilter;
     80 class DomStorageDispatcher;
     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 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 SetOutgoingMessageFilter(
    137       IPC::ChannelProxy::OutgoingMessageFilter* filter) OVERRIDE;
    138   virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
    139   virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
    140   virtual void SetResourceDispatcherDelegate(
    141       ResourceDispatcherDelegate* delegate) OVERRIDE;
    142   virtual void WidgetHidden() OVERRIDE;
    143   virtual void WidgetRestored() OVERRIDE;
    144   virtual void EnsureWebKitInitialized() OVERRIDE;
    145   virtual void RecordUserMetrics(const std::string& action) OVERRIDE;
    146   virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
    147       size_t buffer_size) OVERRIDE;
    148   virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
    149   virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
    150   virtual void IdleHandler() OVERRIDE;
    151   virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
    152   virtual void SetIdleNotificationDelayInMs(
    153       int64 idle_notification_delay_in_ms) OVERRIDE;
    154   virtual void ToggleWebKitSharedTimer(bool suspend) OVERRIDE;
    155   virtual void UpdateHistograms(int sequence_number) OVERRIDE;
    156   virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
    157   virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
    158 #if defined(OS_WIN)
    159   virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
    160   virtual void ReleaseCachedFonts() OVERRIDE;
    161 #endif
    162 
    163   // Synchronously establish a channel to the GPU plugin if not previously
    164   // established or if it has been lost (for example if the GPU plugin crashed).
    165   // If there is a pending asynchronous request, it will be completed by the
    166   // time this routine returns.
    167   virtual GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch) OVERRIDE;
    168 
    169 
    170   // These methods modify how the next message is sent.  Normally, when sending
    171   // a synchronous message that runs a nested message loop, we need to suspend
    172   // callbacks into WebKit.  This involves disabling timers and deferring
    173   // resource loads.  However, there are exceptions when we need to customize
    174   // the behavior.
    175   void DoNotSuspendWebKitSharedTimer();
    176   void DoNotNotifyWebKitOfModalLoop();
    177 
    178   // True if we are running layout tests. This currently disables forwarding
    179   // various status messages to the console, skips network error pages, and
    180   // short circuits size update and focus events.
    181   bool layout_test_mode() const {
    182     return layout_test_mode_;
    183   }
    184   void set_layout_test_mode(bool layout_test_mode) {
    185     layout_test_mode_ = layout_test_mode;
    186   }
    187 
    188   IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
    189     return compositor_output_surface_filter_.get();
    190   }
    191 
    192   InputHandlerManager* input_handler_manager() const {
    193     return input_handler_manager_.get();
    194   }
    195 
    196   // Will be NULL if threaded compositing has not been enabled.
    197   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
    198     return compositor_message_loop_proxy_;
    199   }
    200 
    201   AppCacheDispatcher* appcache_dispatcher() const {
    202     return appcache_dispatcher_.get();
    203   }
    204 
    205   DomStorageDispatcher* dom_storage_dispatcher() const {
    206     return dom_storage_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   // Creates the embedder implementation of WebMediaStreamCenter.
    222   // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
    223   WebKit::WebMediaStreamCenter* CreateMediaStreamCenter(
    224       WebKit::WebMediaStreamCenterClient* client);
    225 
    226   // Returns a factory used for creating RTC PeerConnection objects.
    227   MediaStreamDependencyFactory* GetMediaStreamDependencyFactory();
    228 
    229   PeerConnectionTracker* peer_connection_tracker() {
    230     return peer_connection_tracker_.get();
    231   }
    232 
    233   // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
    234   P2PSocketDispatcher* p2p_socket_dispatcher() {
    235     return p2p_socket_dispatcher_.get();
    236   }
    237 
    238   VideoCaptureImplManager* video_capture_impl_manager() const {
    239     return vc_manager_.get();
    240   }
    241 
    242   // Get the GPU channel. Returns NULL if the channel is not established or
    243   // has been lost.
    244   GpuChannelHost* GetGpuChannel();
    245 
    246   // Returns a MessageLoopProxy instance corresponding to the message loop
    247   // of the thread on which file operations should be run. Must be called
    248   // on the renderer's main thread.
    249   scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
    250 
    251   // Returns a MessageLoopProxy instance corresponding to the message loop
    252   // of the thread on which media operations should be run. Must be called
    253   // on the renderer's main thread.
    254   scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
    255 
    256   // Causes the idle handler to skip sending idle notifications
    257   // on the two next scheduled calls, so idle notifications are
    258   // not sent for at least one notification delay.
    259   void PostponeIdleNotification();
    260 
    261   // Gets gpu factories, which will run on |factories_loop|. Returns NULL if VDA
    262   // is disabled or a graphics context cannot be obtained.
    263   scoped_refptr<RendererGpuVideoDecoderFactories> GetGpuFactories(
    264       const scoped_refptr<base::MessageLoopProxy>& factories_loop);
    265 
    266   // Returns a graphics context shared among all
    267   // RendererGpuVideoDecoderFactories, or NULL on error.  Context remains owned
    268   // by this class and must be null-tested before each use to detect context
    269   // loss.  The returned context is only valid on the compositor thread when
    270   // threaded compositing is enabled.
    271   WebGraphicsContext3DCommandBufferImpl* GetGpuVDAContext3D();
    272 
    273   // Handle loss of the shared GpuVDAContext3D context above.
    274   static void OnGpuVDAContextLoss();
    275 
    276   scoped_refptr<cc::ContextProvider>
    277       OffscreenContextProviderForMainThread();
    278   scoped_refptr<cc::ContextProvider>
    279       OffscreenContextProviderForCompositorThread();
    280 
    281   // AudioRendererMixerManager instance which manages renderer side mixer
    282   // instances shared based on configured audio parameters.  Lazily created on
    283   // first call.
    284   AudioRendererMixerManager* GetAudioRendererMixerManager();
    285 
    286   // AudioHardwareConfig contains audio hardware configuration for
    287   // renderer side clients.  Creation requires a synchronous IPC call so it is
    288   // lazily created on the first call.
    289   media::AudioHardwareConfig* GetAudioHardwareConfig();
    290 
    291 #if defined(OS_WIN)
    292   void PreCacheFontCharacters(const LOGFONT& log_font, const string16& str);
    293 #endif
    294 
    295 #if defined(ENABLE_WEBRTC)
    296   WebRTCIdentityService* get_webrtc_identity_service() {
    297     return webrtc_identity_service_.get();
    298   }
    299 #endif
    300 
    301   // For producing custom V8 histograms. Custom histograms are produced if all
    302   // RenderViews share the same host, and the host is in the pre-specified set
    303   // of hosts we want to produce custom diagrams for. The name for a custom
    304   // diagram is the name of the corresponding generic diagram plus a
    305   // host-specific suffix.
    306   class CONTENT_EXPORT HistogramCustomizer {
    307    public:
    308     HistogramCustomizer();
    309     ~HistogramCustomizer();
    310 
    311     // Called when a top frame of a RenderView navigates. This function updates
    312     // RenderThreadImpl's information about whether all RenderViews are
    313     // displaying a page from the same host. |host| is the host where a
    314     // RenderView navigated, and |view_count| is the number of RenderViews in
    315     // this process.
    316     void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
    317 
    318     // Used for customizing some histograms if all RenderViews share the same
    319     // host. Returns the current custom histogram name to use for
    320     // |histogram_name|, or |histogram_name| if it shouldn't be customized.
    321     std::string ConvertToCustomHistogramName(const char* histogram_name) const;
    322 
    323    private:
    324     friend class RenderThreadImplUnittest;
    325 
    326     // Used for updating the information on which is the common host which all
    327     // RenderView's share (if any). If there is no common host, this function is
    328     // called with an empty string.
    329     void SetCommonHost(const std::string& host);
    330 
    331     // The current common host of the RenderViews; empty string if there is no
    332     // common host.
    333     std::string common_host_;
    334     // The corresponding suffix.
    335     std::string common_host_histogram_suffix_;
    336     // Set of histograms for which we want to produce a custom histogram if
    337     // possible.
    338     std::set<std::string> custom_histograms_;
    339 
    340     DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
    341   };
    342 
    343   HistogramCustomizer* histogram_customizer() {
    344     return &histogram_customizer_;
    345   }
    346 
    347   void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
    348                                const std::vector<float>& new_touchscreen);
    349 
    350   // Retrieve current gamepad data.
    351   void SampleGamepads(WebKit::WebGamepads* data);
    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 
    373   void Init();
    374 
    375   void OnSetZoomLevelForCurrentURL(const std::string& scheme,
    376                                    const std::string& host,
    377                                    double zoom_level);
    378   void OnCreateNewView(const ViewMsg_New_Params& params);
    379   void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
    380   void OnPurgePluginListCache(bool reload_pages);
    381   void OnNetworkStateChanged(bool online);
    382   void OnGetAccessibilityTree();
    383   void OnTempCrashWithData(const GURL& data);
    384   void OnSetWebKitSharedTimersSuspended(bool suspend);
    385   void OnMemoryPressure(
    386       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
    387 
    388   void IdleHandlerInForegroundTab();
    389 
    390   scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
    391 
    392   // These objects live solely on the render thread.
    393   scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
    394   scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
    395   scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
    396   scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
    397 
    398   // Used on the render thread and deleted by WebKit at shutdown.
    399   WebKit::WebMediaStreamCenter* media_stream_center_;
    400 
    401   // Used on the renderer and IPC threads.
    402   scoped_refptr<DBMessageFilter> db_message_filter_;
    403   scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
    404   scoped_refptr<AudioMessageFilter> audio_message_filter_;
    405   scoped_refptr<MIDIMessageFilter> midi_message_filter_;
    406   scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
    407 
    408   scoped_ptr<MediaStreamDependencyFactory> media_stream_factory_;
    409 
    410   // This is used to communicate to the browser process the status
    411   // of all the peer connections created in the renderer.
    412   scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
    413 
    414   // Dispatches all P2P sockets.
    415   scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
    416 
    417   // Used on multiple threads.
    418   scoped_refptr<VideoCaptureImplManager> vc_manager_;
    419 
    420   // Used on multiple script execution context threads.
    421   scoped_ptr<WebDatabaseObserverImpl> web_database_observer_impl_;
    422 
    423 #if defined(OS_WIN)
    424   // Initialize COM when using plugins outside the sandbox.
    425   scoped_ptr<base::win::ScopedCOMInitializer> initialize_com_;
    426 #endif
    427 
    428   // The count of RenderWidgets running through this thread.
    429   int widget_count_;
    430 
    431   // The count of hidden RenderWidgets running through this thread.
    432   int hidden_widget_count_;
    433 
    434   // The current value of the idle notification timer delay.
    435   int64 idle_notification_delay_in_ms_;
    436 
    437   // The number of idle handler calls that skip sending idle notifications.
    438   int idle_notifications_to_skip_;
    439 
    440   bool suspend_webkit_shared_timer_;
    441   bool notify_webkit_of_modal_loop_;
    442 
    443   // The following flag is used to control layout test specific behavior.
    444   bool layout_test_mode_;
    445 
    446   // Timer that periodically calls IdleHandler.
    447   base::RepeatingTimer<RenderThreadImpl> idle_timer_;
    448 
    449   // The channel from the renderer process to the GPU process.
    450   scoped_refptr<GpuChannelHost> gpu_channel_;
    451 
    452   // Cache of variables that are needed on the compositor thread by
    453   // GpuChannelHostFactory methods.
    454   scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
    455   base::WaitableEvent* shutdown_event_;
    456 
    457   // A lazily initiated thread on which file operations are run.
    458   scoped_ptr<base::Thread> file_thread_;
    459 
    460   // May be null if overridden by ContentRendererClient.
    461   scoped_ptr<base::Thread> compositor_thread_;
    462 
    463   // Thread for running multimedia operations (e.g., video decoding).
    464   scoped_ptr<base::Thread> media_thread_;
    465 
    466   // Will point to appropriate MessageLoopProxy after initialization,
    467   // regardless of whether |compositor_thread_| is overriden.
    468   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
    469 
    470   // May be null if unused by the |input_handler_manager_|.
    471   scoped_refptr<InputEventFilter> input_event_filter_;
    472   scoped_ptr<InputHandlerManager> input_handler_manager_;
    473   scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
    474 
    475   scoped_refptr<ContextProviderCommandBuffer> shared_contexts_main_thread_;
    476   scoped_refptr<ContextProviderCommandBuffer>
    477       shared_contexts_compositor_thread_;
    478 
    479   ObserverList<RenderProcessObserver> observers_;
    480 
    481   class GpuVDAContextLostCallback;
    482   scoped_ptr<GpuVDAContextLostCallback> context_lost_cb_;
    483   scoped_ptr<WebGraphicsContext3DCommandBufferImpl> gpu_vda_context3d_;
    484 
    485   scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
    486   scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
    487 
    488   HistogramCustomizer histogram_customizer_;
    489 
    490   scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
    491 
    492   scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
    493 
    494   scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
    495 
    496   DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
    497 };
    498 
    499 }  // namespace content
    500 
    501 #endif  // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
    502