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/process/process_handle.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 class GrContext;
     28 class SkBitmap;
     29 struct ViewMsg_New_Params;
     30 
     31 namespace blink {
     32 class WebGamepads;
     33 class WebGraphicsContext3D;
     34 class WebMediaStreamCenter;
     35 class WebMediaStreamCenterClient;
     36 }
     37 
     38 namespace base {
     39 class MessageLoopProxy;
     40 class Thread;
     41 
     42 #if defined(OS_WIN)
     43 namespace win {
     44 class ScopedCOMInitializer;
     45 }
     46 #endif
     47 }
     48 
     49 namespace cc {
     50 class ContextProvider;
     51 }
     52 
     53 namespace IPC {
     54 class ForwardingMessageFilter;
     55 }
     56 
     57 namespace media {
     58 class AudioHardwareConfig;
     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 EmbeddedWorkerDispatcher;
     82 class GamepadSharedMemoryReader;
     83 class GpuChannelHost;
     84 class IndexedDBDispatcher;
     85 class InputEventFilter;
     86 class InputHandlerManager;
     87 class MediaStreamCenter;
     88 class MediaStreamDependencyFactory;
     89 class MIDIMessageFilter;
     90 class P2PSocketDispatcher;
     91 class PeerConnectionTracker;
     92 class RendererDemuxerAndroid;
     93 class RendererWebKitPlatformSupportImpl;
     94 class RenderProcessObserver;
     95 class VideoCaptureImplManager;
     96 class WebGraphicsContext3DCommandBufferImpl;
     97 class WebRTCIdentityService;
     98 
     99 // The RenderThreadImpl class represents a background thread where RenderView
    100 // instances live.  The RenderThread supports an API that is used by its
    101 // consumer to talk indirectly to the RenderViews and supporting objects.
    102 // Likewise, it provides an API for the RenderViews to talk back to the main
    103 // process (i.e., their corresponding WebContentsImpl).
    104 //
    105 // Most of the communication occurs in the form of IPC messages.  They are
    106 // routed to the RenderThread according to the routing IDs of the messages.
    107 // The routing IDs correspond to RenderView instances.
    108 class CONTENT_EXPORT RenderThreadImpl : public RenderThread,
    109                                         public ChildThread,
    110                                         public GpuChannelHostFactory {
    111  public:
    112   static RenderThreadImpl* current();
    113 
    114   RenderThreadImpl();
    115   // Constructor that's used when running in single process mode.
    116   explicit RenderThreadImpl(const std::string& channel_name);
    117   virtual ~RenderThreadImpl();
    118   virtual void Shutdown() OVERRIDE;
    119 
    120   // When initializing WebKit, ensure that any schemes needed for the content
    121   // module are registered properly.  Static to allow sharing with tests.
    122   static void RegisterSchemes();
    123 
    124   // RenderThread implementation:
    125   virtual bool Send(IPC::Message* msg) OVERRIDE;
    126   virtual base::MessageLoop* GetMessageLoop() OVERRIDE;
    127   virtual IPC::SyncChannel* GetChannel() OVERRIDE;
    128   virtual std::string GetLocale() OVERRIDE;
    129   virtual IPC::SyncMessageFilter* GetSyncMessageFilter() OVERRIDE;
    130   virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy()
    131       OVERRIDE;
    132   virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
    133   virtual void RemoveRoute(int32 routing_id) OVERRIDE;
    134   virtual int GenerateRoutingID() OVERRIDE;
    135   virtual void AddFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
    136   virtual void RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) OVERRIDE;
    137   virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
    138   virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
    139   virtual void SetResourceDispatcherDelegate(
    140       ResourceDispatcherDelegate* delegate) OVERRIDE;
    141   virtual void WidgetHidden() OVERRIDE;
    142   virtual void WidgetRestored() OVERRIDE;
    143   virtual void EnsureWebKitInitialized() OVERRIDE;
    144   virtual void RecordAction(const UserMetricsAction& action) OVERRIDE;
    145   virtual void RecordComputedAction(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   GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
    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   EmbeddedWorkerDispatcher* embedded_worker_dispatcher() const {
    210     return embedded_worker_dispatcher_.get();
    211   }
    212 
    213   AudioInputMessageFilter* audio_input_message_filter() {
    214     return audio_input_message_filter_.get();
    215   }
    216 
    217   AudioMessageFilter* audio_message_filter() {
    218     return audio_message_filter_.get();
    219   }
    220 
    221   MIDIMessageFilter* midi_message_filter() {
    222     return midi_message_filter_.get();
    223   }
    224 
    225 #if defined(OS_ANDROID)
    226   RendererDemuxerAndroid* renderer_demuxer() {
    227     return renderer_demuxer_.get();
    228   }
    229 #endif
    230 
    231   // Creates the embedder implementation of WebMediaStreamCenter.
    232   // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
    233   blink::WebMediaStreamCenter* CreateMediaStreamCenter(
    234       blink::WebMediaStreamCenterClient* client);
    235 
    236   // Returns a factory used for creating RTC PeerConnection objects.
    237   MediaStreamDependencyFactory* GetMediaStreamDependencyFactory();
    238 
    239   PeerConnectionTracker* peer_connection_tracker() {
    240     return peer_connection_tracker_.get();
    241   }
    242 
    243   // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
    244   P2PSocketDispatcher* p2p_socket_dispatcher() {
    245     return p2p_socket_dispatcher_.get();
    246   }
    247 
    248   VideoCaptureImplManager* video_capture_impl_manager() const {
    249     return vc_manager_.get();
    250   }
    251 
    252   // Get the GPU channel. Returns NULL if the channel is not established or
    253   // has been lost.
    254   GpuChannelHost* GetGpuChannel();
    255 
    256   // Returns a MessageLoopProxy instance corresponding to the message loop
    257   // of the thread on which file operations should be run. Must be called
    258   // on the renderer's main thread.
    259   scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
    260 
    261   // Returns a MessageLoopProxy instance corresponding to the message loop
    262   // of the thread on which media operations should be run. Must be called
    263   // on the renderer's main thread.
    264   scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
    265 
    266   // Causes the idle handler to skip sending idle notifications
    267   // on the two next scheduled calls, so idle notifications are
    268   // not sent for at least one notification delay.
    269   void PostponeIdleNotification();
    270 
    271   scoped_refptr<RendererGpuVideoAcceleratorFactories> GetGpuFactories();
    272 
    273   scoped_refptr<cc::ContextProvider> OffscreenCompositorContextProvider();
    274   scoped_refptr<cc::ContextProvider> SharedMainThreadContextProvider();
    275 
    276   // AudioRendererMixerManager instance which manages renderer side mixer
    277   // instances shared based on configured audio parameters.  Lazily created on
    278   // first call.
    279   AudioRendererMixerManager* GetAudioRendererMixerManager();
    280 
    281   // AudioHardwareConfig contains audio hardware configuration for
    282   // renderer side clients.  Creation requires a synchronous IPC call so it is
    283   // lazily created on the first call.
    284   media::AudioHardwareConfig* GetAudioHardwareConfig();
    285 
    286 #if defined(OS_WIN)
    287   void PreCacheFontCharacters(const LOGFONT& log_font,
    288                               const base::string16& str);
    289 #endif
    290 
    291 #if defined(ENABLE_WEBRTC)
    292   WebRTCIdentityService* get_webrtc_identity_service() {
    293     return webrtc_identity_service_.get();
    294   }
    295 #endif
    296 
    297   // For producing custom V8 histograms. Custom histograms are produced if all
    298   // RenderViews share the same host, and the host is in the pre-specified set
    299   // of hosts we want to produce custom diagrams for. The name for a custom
    300   // diagram is the name of the corresponding generic diagram plus a
    301   // host-specific suffix.
    302   class CONTENT_EXPORT HistogramCustomizer {
    303    public:
    304     HistogramCustomizer();
    305     ~HistogramCustomizer();
    306 
    307     // Called when a top frame of a RenderView navigates. This function updates
    308     // RenderThreadImpl's information about whether all RenderViews are
    309     // displaying a page from the same host. |host| is the host where a
    310     // RenderView navigated, and |view_count| is the number of RenderViews in
    311     // this process.
    312     void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
    313 
    314     // Used for customizing some histograms if all RenderViews share the same
    315     // host. Returns the current custom histogram name to use for
    316     // |histogram_name|, or |histogram_name| if it shouldn't be customized.
    317     std::string ConvertToCustomHistogramName(const char* histogram_name) const;
    318 
    319    private:
    320     friend class RenderThreadImplUnittest;
    321 
    322     // Used for updating the information on which is the common host which all
    323     // RenderView's share (if any). If there is no common host, this function is
    324     // called with an empty string.
    325     void SetCommonHost(const std::string& host);
    326 
    327     // The current common host of the RenderViews; empty string if there is no
    328     // common host.
    329     std::string common_host_;
    330     // The corresponding suffix.
    331     std::string common_host_histogram_suffix_;
    332     // Set of histograms for which we want to produce a custom histogram if
    333     // possible.
    334     std::set<std::string> custom_histograms_;
    335 
    336     DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
    337   };
    338 
    339   HistogramCustomizer* histogram_customizer() {
    340     return &histogram_customizer_;
    341   }
    342 
    343   void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
    344                                const std::vector<float>& new_touchscreen);
    345 
    346   // Retrieve current gamepad data.
    347   void SampleGamepads(blink::WebGamepads* data);
    348 
    349   // Get the browser process's notion of the renderer process's ID.
    350   // This is the first argument to RenderWidgetHost::FromID. Ideally
    351   // this would be available on all platforms via base::Process.
    352   base::ProcessId renderer_process_id() const;
    353 
    354  private:
    355   // ChildThread
    356   virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
    357 
    358   // GpuChannelHostFactory implementation:
    359   virtual bool IsMainThread() OVERRIDE;
    360   virtual base::MessageLoop* GetMainLoop() OVERRIDE;
    361   virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
    362   virtual base::WaitableEvent* GetShutDownEvent() OVERRIDE;
    363   virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
    364       size_t size) OVERRIDE;
    365   virtual int32 CreateViewCommandBuffer(
    366       int32 surface_id,
    367       const GPUCreateCommandBufferConfig& init_params) OVERRIDE;
    368   virtual void CreateImage(
    369       gfx::PluginWindowHandle window,
    370       int32 image_id,
    371       const CreateImageCallback& callback) OVERRIDE;
    372   virtual void DeleteImage(int32 image_id, int32 sync_point) OVERRIDE;
    373   virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
    374       size_t width,
    375       size_t height,
    376       unsigned internalformat) OVERRIDE;
    377 
    378   void Init();
    379 
    380   void OnSetZoomLevelForCurrentURL(const std::string& scheme,
    381                                    const std::string& host,
    382                                    double zoom_level);
    383   void OnCreateNewView(const ViewMsg_New_Params& params);
    384   void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
    385   void OnPurgePluginListCache(bool reload_pages);
    386   void OnNetworkStateChanged(bool online);
    387   void OnGetAccessibilityTree();
    388   void OnTempCrashWithData(const GURL& data);
    389   void OnSetRendererProcessID(base::ProcessId process_id);
    390   void OnMemoryPressure(
    391       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
    392 #if defined(OS_ANDROID)
    393   void OnSetWebKitSharedTimersSuspended(bool suspend);
    394 #endif
    395 #if defined(OS_MACOSX)
    396   void OnUpdateScrollbarTheme(float initial_button_delay,
    397                               float autoscroll_button_delay,
    398                               bool jump_on_track_click,
    399                               bool redraw);
    400 #endif
    401 
    402   void IdleHandlerInForegroundTab();
    403 
    404   scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
    405 
    406   // These objects live solely on the render thread.
    407   scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
    408   scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
    409   scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
    410   scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
    411   scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
    412 
    413   // Used on the render thread and deleted by WebKit at shutdown.
    414   blink::WebMediaStreamCenter* media_stream_center_;
    415 
    416   // Used on the renderer and IPC threads.
    417   scoped_refptr<DBMessageFilter> db_message_filter_;
    418   scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
    419   scoped_refptr<AudioMessageFilter> audio_message_filter_;
    420   scoped_refptr<MIDIMessageFilter> midi_message_filter_;
    421 #if defined(OS_ANDROID)
    422   scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
    423 #endif
    424   scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
    425 
    426   scoped_ptr<MediaStreamDependencyFactory> media_stream_factory_;
    427 
    428   // This is used to communicate to the browser process the status
    429   // of all the peer connections created in the renderer.
    430   scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
    431 
    432   // Dispatches all P2P sockets.
    433   scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
    434 
    435   // Used on multiple threads.
    436   scoped_refptr<VideoCaptureImplManager> vc_manager_;
    437 
    438 #if defined(OS_WIN)
    439   // Initialize COM when using plugins outside the sandbox.
    440   scoped_ptr<base::win::ScopedCOMInitializer> initialize_com_;
    441 #endif
    442 
    443   // The count of RenderWidgets running through this thread.
    444   int widget_count_;
    445 
    446   // The count of hidden RenderWidgets running through this thread.
    447   int hidden_widget_count_;
    448 
    449   // The current value of the idle notification timer delay.
    450   int64 idle_notification_delay_in_ms_;
    451 
    452   // The number of idle handler calls that skip sending idle notifications.
    453   int idle_notifications_to_skip_;
    454 
    455   bool suspend_webkit_shared_timer_;
    456   bool notify_webkit_of_modal_loop_;
    457 
    458   // The following flag is used to control layout test specific behavior.
    459   bool layout_test_mode_;
    460 
    461   // Timer that periodically calls IdleHandler.
    462   base::RepeatingTimer<RenderThreadImpl> idle_timer_;
    463 
    464   // The channel from the renderer process to the GPU process.
    465   scoped_refptr<GpuChannelHost> gpu_channel_;
    466 
    467   // Cache of variables that are needed on the compositor thread by
    468   // GpuChannelHostFactory methods.
    469   scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
    470   base::WaitableEvent* shutdown_event_;
    471 
    472   // A lazily initiated thread on which file operations are run.
    473   scoped_ptr<base::Thread> file_thread_;
    474 
    475   // May be null if overridden by ContentRendererClient.
    476   scoped_ptr<base::Thread> compositor_thread_;
    477 
    478   // Thread for running multimedia operations (e.g., video decoding).
    479   scoped_ptr<base::Thread> media_thread_;
    480 
    481   // Will point to appropriate MessageLoopProxy after initialization,
    482   // regardless of whether |compositor_thread_| is overriden.
    483   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
    484 
    485   // May be null if unused by the |input_handler_manager_|.
    486   scoped_refptr<InputEventFilter> input_event_filter_;
    487   scoped_ptr<InputHandlerManager> input_handler_manager_;
    488   scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
    489 
    490   scoped_refptr<ContextProviderCommandBuffer> offscreen_compositor_contexts_;
    491   scoped_refptr<ContextProviderCommandBuffer> shared_main_thread_contexts_;
    492 
    493   ObserverList<RenderProcessObserver> observers_;
    494 
    495   scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
    496 
    497   scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
    498   scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
    499 
    500   HistogramCustomizer histogram_customizer_;
    501 
    502   scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
    503 
    504   scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
    505 
    506   scoped_ptr<GamepadSharedMemoryReader> gamepad_shared_memory_reader_;
    507 
    508   base::ProcessId renderer_process_id_;
    509 
    510   // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
    511   // multiple threads. Current allocation mechanism for IOSurface
    512   // backed GpuMemoryBuffers prevent this. crbug.com/325045
    513   base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_;
    514 
    515   DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
    516 };
    517 
    518 }  // namespace content
    519 
    520 #endif  // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
    521