b88425f8da90cb2bfe2a48d786efe9eb544aadac
[platform/framework/web/chromium-efl.git] / 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 <stddef.h>
9 #include <stdint.h>
10
11 #include <map>
12 #include <memory>
13 #include <set>
14 #include <string>
15 #include <utility>
16 #include <vector>
17
18 #include "base/cancelable_callback.h"
19 #include "base/macros.h"
20 #include "base/memory/memory_coordinator_client.h"
21 #include "base/memory/memory_pressure_listener.h"
22 #include "base/memory/ref_counted.h"
23 #include "base/metrics/user_metrics_action.h"
24 #include "base/observer_list.h"
25 #include "base/optional.h"
26 #include "base/strings/string16.h"
27 #include "base/threading/thread_checker.h"
28 #include "base/time/time.h"
29 #include "base/timer/timer.h"
30 #include "build/build_config.h"
31 #include "content/child/child_thread_impl.h"
32 #include "content/child/memory/child_memory_coordinator_impl.h"
33 #include "content/common/associated_interface_registry_impl.h"
34 #include "content/common/content_export.h"
35 #include "content/common/frame.mojom.h"
36 #include "content/common/frame_replication_state.h"
37 #include "content/common/frame_sink_provider.mojom.h"
38 #include "content/common/render_frame_message_filter.mojom.h"
39 #include "content/common/render_frame_metadata.mojom.h"
40 #include "content/common/render_message_filter.mojom.h"
41 #include "content/common/renderer.mojom.h"
42 #include "content/common/renderer_host.mojom.h"
43 #include "content/common/storage_partition_service.mojom.h"
44 #include "content/public/renderer/render_thread.h"
45 #include "content/public/renderer/url_loader_throttle_provider.h"
46 #include "content/renderer/gpu/compositor_dependencies.h"
47 #include "content/renderer/layout_test_dependencies.h"
48 #include "content/renderer/media/audio_input_ipc_factory.h"
49 #include "content/renderer/media/audio_output_ipc_factory.h"
50 #include "gpu/ipc/client/gpu_channel_host.h"
51 #include "ipc/ipc_sync_channel.h"
52 #include "media/media_buildflags.h"
53 #include "mojo/public/cpp/bindings/associated_binding.h"
54 #include "mojo/public/cpp/bindings/binding.h"
55 #include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
56 #include "net/base/network_change_notifier.h"
57 #include "net/nqe/effective_connection_type.h"
58 #include "services/network/public/mojom/url_loader_factory.mojom.h"
59 #include "services/service_manager/public/cpp/bind_source_info.h"
60 #include "services/service_manager/public/cpp/binder_registry.h"
61 #include "services/viz/public/interfaces/compositing/compositing_mode_watcher.mojom.h"
62 #include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
63 #include "third_party/blink/public/platform/web_connection_type.h"
64 #include "third_party/blink/public/web/web_memory_statistics.h"
65 #include "ui/gfx/native_widget_types.h"
66
67 #if defined(OS_MACOSX)
68 #include "third_party/blink/public/platform/mac/web_scrollbar_theme.h"
69 #endif
70
71 class SkBitmap;
72
73 namespace blink {
74 namespace scheduler {
75 class WebThreadBase;
76 }
77 class WebMediaStreamCenter;
78 class WebMediaStreamCenterClient;
79 }
80
81 namespace base {
82 class SingleThreadTaskRunner;
83 class Thread;
84 }
85
86 namespace cc {
87 class BeginFrameSource;
88 class LayerTreeFrameSink;
89 class SyntheticBeginFrameSource;
90 class TaskGraphRunner;
91 }
92
93 namespace device {
94 class Gamepads;
95 }
96
97 namespace discardable_memory {
98 class ClientDiscardableSharedMemoryManager;
99 }
100
101 namespace gpu {
102 class GpuChannelHost;
103 }
104
105 namespace IPC {
106 class MessageFilter;
107 }
108
109 namespace media {
110 class GpuVideoAcceleratorFactories;
111 }
112
113 namespace ui {
114 class ContextProviderCommandBuffer;
115 class Gpu;
116 }
117
118 namespace v8 {
119 class Extension;
120 }
121
122 namespace viz {
123 class BeginFrameSource;
124 class ClientSharedBitmapManager;
125 class RasterContextProvider;
126 class SyntheticBeginFrameSource;
127 }
128
129 namespace content {
130
131 class AppCacheDispatcher;
132 class AecDumpMessageFilter;
133 class AudioMessageFilter;
134 class AudioRendererMixerManager;
135 class BrowserPluginManager;
136 class CategorizedWorkerPool;
137 class DomStorageDispatcher;
138 class FileSystemDispatcher;
139 class FrameSwapMessageQueue;
140 class GpuVideoAcceleratorFactoriesImpl;
141 class IndexedDBDispatcher;
142 class InputHandlerManager;
143 class MidiMessageFilter;
144 class NotificationDispatcher;
145 class P2PSocketDispatcher;
146 class PeerConnectionDependencyFactory;
147 class PeerConnectionTracker;
148 class RenderThreadObserver;
149 class RendererBlinkPlatformImpl;
150 class ResourceDispatcher;
151 class ServiceWorkerMessageFilter;
152 class VideoCaptureImplManager;
153
154 #if defined(OS_ANDROID)
155 class StreamTextureFactory;
156 class SynchronousCompositorFilter;
157 #endif
158
159 #if defined(COMPILER_MSVC)
160 // See explanation for other RenderViewHostImpl which is the same issue.
161 #pragma warning(push)
162 #pragma warning(disable: 4250)
163 #endif
164
165 // The RenderThreadImpl class represents a background thread where RenderView
166 // instances live.  The RenderThread supports an API that is used by its
167 // consumer to talk indirectly to the RenderViews and supporting objects.
168 // Likewise, it provides an API for the RenderViews to talk back to the main
169 // process (i.e., their corresponding WebContentsImpl).
170 //
171 // Most of the communication occurs in the form of IPC messages.  They are
172 // routed to the RenderThread according to the routing IDs of the messages.
173 // The routing IDs correspond to RenderView instances.
174 class CONTENT_EXPORT RenderThreadImpl
175     : public RenderThread,
176       public ChildThreadImpl,
177       public blink::scheduler::WebMainThreadScheduler::RAILModeObserver,
178       public ChildMemoryCoordinatorDelegate,
179       public base::MemoryCoordinatorClient,
180       public mojom::Renderer,
181       public viz::mojom::CompositingModeWatcher,
182       public CompositorDependencies {
183  public:
184   static RenderThreadImpl* Create(const InProcessChildThreadParams& params,
185                                   base::MessageLoop* unowned_message_loop);
186   static RenderThreadImpl* Create(
187       std::unique_ptr<base::MessageLoop> main_message_loop,
188       std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
189           main_thread_scheduler);
190   static RenderThreadImpl* current();
191   static mojom::RenderMessageFilter* current_render_message_filter();
192   static RendererBlinkPlatformImpl* current_blink_platform_impl();
193
194   static void SetRenderMessageFilterForTesting(
195       mojom::RenderMessageFilter* render_message_filter);
196   static void SetRendererBlinkPlatformImplForTesting(
197       RendererBlinkPlatformImpl* blink_platform_impl);
198
199   // Returns the task runner for the main thread where the RenderThread lives.
200   static scoped_refptr<base::SingleThreadTaskRunner>
201   DeprecatedGetMainTaskRunner();
202
203   ~RenderThreadImpl() override;
204   void Shutdown() override;
205   bool ShouldBeDestroyed() override;
206
207   // When initializing WebKit, ensure that any schemes needed for the content
208   // module are registered properly.  Static to allow sharing with tests.
209   static void RegisterSchemes();
210
211   // RenderThread implementation:
212   bool Send(IPC::Message* msg) override;
213   IPC::SyncChannel* GetChannel() override;
214   std::string GetLocale() override;
215   IPC::SyncMessageFilter* GetSyncMessageFilter() override;
216   void AddRoute(int32_t routing_id, IPC::Listener* listener) override;
217   void RemoveRoute(int32_t routing_id) override;
218   int GenerateRoutingID() override;
219   void AddFilter(IPC::MessageFilter* filter) override;
220   void RemoveFilter(IPC::MessageFilter* filter) override;
221   void AddObserver(RenderThreadObserver* observer) override;
222   void RemoveObserver(RenderThreadObserver* observer) override;
223   void SetResourceDispatcherDelegate(
224       ResourceDispatcherDelegate* delegate) override;
225   std::unique_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
226       size_t buffer_size) override;
227   viz::SharedBitmapManager* GetSharedBitmapManager() override;
228   void RegisterExtension(v8::Extension* extension) override;
229   void ScheduleIdleHandler(int64_t initial_delay_ms) override;
230   void IdleHandler() override;
231   int64_t GetIdleNotificationDelayInMs() const override;
232   void SetIdleNotificationDelayInMs(
233       int64_t idle_notification_delay_in_ms) override;
234   int PostTaskToAllWebWorkers(const base::Closure& closure) override;
235   bool ResolveProxy(const GURL& url, std::string* proxy_list) override;
236   base::WaitableEvent* GetShutdownEvent() override;
237   int32_t GetClientId() override;
238   void SetRendererProcessType(
239       blink::scheduler::RendererProcessType type) override;
240
241   // IPC::Listener implementation via ChildThreadImpl:
242   bool OnMessageReceived(const IPC::Message& msg) override;
243   void OnAssociatedInterfaceRequest(
244       const std::string& name,
245       mojo::ScopedInterfaceEndpointHandle handle) override;
246
247   // ChildThread implementation via ChildThreadImpl:
248   scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() override;
249
250   // CompositorDependencies implementation.
251   bool IsGpuRasterizationForced() override;
252   int GetGpuRasterizationMSAASampleCount() override;
253   bool IsLcdTextEnabled() override;
254   bool IsZeroCopyEnabled() override;
255   bool IsPartialRasterEnabled() override;
256   bool IsGpuMemoryBufferCompositorResourcesEnabled() override;
257   bool IsElasticOverscrollEnabled() override;
258   scoped_refptr<base::SingleThreadTaskRunner>
259   GetCompositorMainThreadTaskRunner() override;
260   scoped_refptr<base::SingleThreadTaskRunner>
261   GetCompositorImplThreadTaskRunner() override;
262   blink::scheduler::WebMainThreadScheduler* GetWebMainThreadScheduler()
263       override;
264   cc::TaskGraphRunner* GetTaskGraphRunner() override;
265   bool IsThreadedAnimationEnabled() override;
266   bool IsScrollAnimatorEnabled() override;
267   std::unique_ptr<cc::UkmRecorderFactory> CreateUkmRecorderFactory() override;
268
269   // blink::scheduler::WebMainThreadScheduler::RAILModeObserver implementation.
270   void OnRAILModeChanged(v8::RAILMode rail_mode) override;
271
272   // viz::mojom::CompositingModeWatcher implementation.
273   void CompositingModeFallbackToSoftware() override;
274
275   // Whether gpu compositing is being used or is disabled for software
276   // compositing. Clients of the compositor should give resources that match
277   // the appropriate mode.
278   bool IsGpuCompositingDisabled() { return is_gpu_compositing_disabled_; }
279
280   // Synchronously establish a channel to the GPU plugin if not previously
281   // established or if it has been lost (for example if the GPU plugin crashed).
282   // If there is a pending asynchronous request, it will be completed by the
283   // time this routine returns.
284   scoped_refptr<gpu::GpuChannelHost> EstablishGpuChannelSync();
285
286   gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager();
287
288   using LayerTreeFrameSinkCallback =
289       base::Callback<void(std::unique_ptr<cc::LayerTreeFrameSink>)>;
290   void RequestNewLayerTreeFrameSink(
291       int routing_id,
292       scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
293       const GURL& url,
294       const LayerTreeFrameSinkCallback& callback,
295       mojom::RenderFrameMetadataObserverClientRequest
296           render_frame_metadata_observer_client_request,
297       mojom::RenderFrameMetadataObserverPtr render_frame_metadata_observer_ptr);
298
299   blink::AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry();
300
301   std::unique_ptr<cc::SwapPromise> RequestCopyOfOutputForLayoutTest(
302       int32_t routing_id,
303       std::unique_ptr<viz::CopyOutputRequest> request);
304
305   // True if we are running layout tests. This currently disables forwarding
306   // various status messages to the console, skips network error pages, and
307   // short circuits size update and focus events.
308   bool layout_test_mode() const { return !!layout_test_deps_; }
309   void set_layout_test_dependencies(
310       std::unique_ptr<LayoutTestDependencies> deps) {
311     layout_test_deps_ = std::move(deps);
312   }
313
314   discardable_memory::ClientDiscardableSharedMemoryManager*
315   GetDiscardableSharedMemoryManagerForTest() {
316     return discardable_shared_memory_manager_.get();
317   }
318
319   RendererBlinkPlatformImpl* blink_platform_impl() const {
320     DCHECK(blink_platform_impl_);
321     return blink_platform_impl_.get();
322   }
323
324   InputHandlerManager* input_handler_manager() const {
325     return input_handler_manager_.get();
326   }
327
328   // Will be null if threaded compositing has not been enabled.
329   scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner() const {
330     return compositor_task_runner_;
331   }
332
333   AppCacheDispatcher* appcache_dispatcher() const {
334     return appcache_dispatcher_.get();
335   }
336
337   DomStorageDispatcher* dom_storage_dispatcher() const {
338     return dom_storage_dispatcher_.get();
339   }
340
341   FileSystemDispatcher* file_system_dispatcher() const {
342     return file_system_dispatcher_.get();
343   }
344
345   MidiMessageFilter* midi_message_filter() {
346     return midi_message_filter_.get();
347   }
348
349   ResourceDispatcher* resource_dispatcher() const {
350     return resource_dispatcher_.get();
351   }
352
353   URLLoaderThrottleProvider* url_loader_throttle_provider() const {
354     return url_loader_throttle_provider_.get();
355   }
356
357 #if defined(OS_ANDROID)
358   SynchronousCompositorFilter* sync_compositor_message_filter() {
359     return sync_compositor_message_filter_.get();
360   }
361
362   scoped_refptr<StreamTextureFactory> GetStreamTexureFactory();
363   bool EnableStreamTextureCopy();
364 #endif
365
366   // Creates the embedder implementation of WebMediaStreamCenter.
367   // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
368   std::unique_ptr<blink::WebMediaStreamCenter> CreateMediaStreamCenter(
369       blink::WebMediaStreamCenterClient* client);
370
371   BrowserPluginManager* browser_plugin_manager() const {
372     return browser_plugin_manager_.get();
373   }
374
375 #if BUILDFLAG(ENABLE_WEBRTC)
376   // Returns a factory used for creating RTC PeerConnection objects.
377   PeerConnectionDependencyFactory* GetPeerConnectionDependencyFactory();
378
379   PeerConnectionTracker* peer_connection_tracker() {
380     return peer_connection_tracker_.get();
381   }
382
383   // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
384   P2PSocketDispatcher* p2p_socket_dispatcher() {
385     return p2p_socket_dispatcher_.get();
386   }
387 #endif
388
389   VideoCaptureImplManager* video_capture_impl_manager() const {
390     return vc_manager_.get();
391   }
392
393   viz::ClientSharedBitmapManager* shared_bitmap_manager() const {
394     DCHECK(shared_bitmap_manager_);
395     return shared_bitmap_manager_.get();
396   }
397
398   NotificationDispatcher* notification_dispatcher() const {
399     return notification_dispatcher_.get();
400   }
401
402   mojom::RenderFrameMessageFilter* render_frame_message_filter();
403   mojom::RenderMessageFilter* render_message_filter();
404
405   // Get the GPU channel. Returns NULL if the channel is not established or
406   // has been lost.
407   gpu::GpuChannelHost* GetGpuChannel();
408
409   // Returns a SingleThreadTaskRunner instance corresponding to the message loop
410   // of the thread on which media operations should be run. Must be called
411   // on the renderer's main thread.
412   scoped_refptr<base::SingleThreadTaskRunner> GetMediaThreadTaskRunner();
413
414   // A TaskRunner instance that runs tasks on the raster worker pool.
415   base::TaskRunner* GetWorkerTaskRunner();
416
417   // Returns a worker context provider that will be bound on the compositor
418   // thread.
419   scoped_refptr<viz::RasterContextProvider>
420   SharedCompositorWorkerContextProvider();
421
422   // Causes the idle handler to skip sending idle notifications
423   // on the two next scheduled calls, so idle notifications are
424   // not sent for at least one notification delay.
425   void PostponeIdleNotification();
426
427   media::GpuVideoAcceleratorFactories* GetGpuFactories();
428
429   scoped_refptr<ui::ContextProviderCommandBuffer>
430   SharedMainThreadContextProvider();
431
432   // AudioRendererMixerManager instance which manages renderer side mixer
433   // instances shared based on configured audio parameters.  Lazily created on
434   // first call.
435   AudioRendererMixerManager* GetAudioRendererMixerManager();
436
437 #if defined(OS_WIN)
438   void PreCacheFontCharacters(const LOGFONT& log_font,
439                               const base::string16& str);
440 #endif
441
442   // For producing custom V8 histograms. Custom histograms are produced if all
443   // RenderViews share the same host, and the host is in the pre-specified set
444   // of hosts we want to produce custom diagrams for. The name for a custom
445   // diagram is the name of the corresponding generic diagram plus a
446   // host-specific suffix.
447   class CONTENT_EXPORT HistogramCustomizer {
448    public:
449     HistogramCustomizer();
450     ~HistogramCustomizer();
451
452     // Called when a top frame of a RenderView navigates. This function updates
453     // RenderThreadImpl's information about whether all RenderViews are
454     // displaying a page from the same host. |host| is the host where a
455     // RenderView navigated, and |view_count| is the number of RenderViews in
456     // this process.
457     void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
458
459     // Used for customizing some histograms if all RenderViews share the same
460     // host. Returns the current custom histogram name to use for
461     // |histogram_name|, or |histogram_name| if it shouldn't be customized.
462     std::string ConvertToCustomHistogramName(const char* histogram_name) const;
463
464    private:
465     FRIEND_TEST_ALL_PREFIXES(RenderThreadImplUnittest,
466                              IdentifyAlexaTop10NonGoogleSite);
467     friend class RenderThreadImplUnittest;
468
469     // Converts a host name to a suffix for histograms
470     std::string HostToCustomHistogramSuffix(const std::string& host);
471
472     // Helper function to identify a certain set of top pages
473     bool IsAlexaTop10NonGoogleSite(const std::string& host);
474
475     // Used for updating the information on which is the common host which all
476     // RenderView's share (if any). If there is no common host, this function is
477     // called with an empty string.
478     void SetCommonHost(const std::string& host);
479
480     // The current common host of the RenderViews; empty string if there is no
481     // common host.
482     std::string common_host_;
483     // The corresponding suffix.
484     std::string common_host_histogram_suffix_;
485     // Set of histograms for which we want to produce a custom histogram if
486     // possible.
487     std::set<std::string> custom_histograms_;
488
489     DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
490   };
491
492   HistogramCustomizer* histogram_customizer() {
493     return &histogram_customizer_;
494   }
495
496   // Retrieve current gamepad data.
497   void SampleGamepads(device::Gamepads* data);
498
499   // Called by a RenderWidget when it is created or destroyed. This
500   // allows the process to know when there are no visible widgets.
501   void WidgetCreated();
502   // Note: A widget must not be hidden when it is destroyed - ensure that
503   // WidgetRestored is called before WidgetDestroyed for any hidden widget.
504   void WidgetDestroyed();
505   void WidgetHidden();
506   void WidgetRestored();
507
508   void RegisterPendingFrameCreate(
509       const service_manager::BindSourceInfo& source_info,
510       int routing_id,
511       mojom::FrameRequest frame);
512
513   mojom::StoragePartitionService* GetStoragePartitionService();
514   mojom::RendererHost* GetRendererHost();
515
516   // ChildMemoryCoordinatorDelegate implementation.
517   void OnTrimMemoryImmediately() override;
518
519   struct RendererMemoryMetrics {
520     size_t partition_alloc_kb;
521     size_t blink_gc_kb;
522     size_t malloc_mb;
523     size_t discardable_kb;
524     size_t v8_main_thread_isolate_mb;
525     size_t total_allocated_mb;
526     size_t non_discardable_total_allocated_mb;
527     size_t total_allocated_per_render_view_mb;
528   };
529   bool GetRendererMemoryMetrics(RendererMemoryMetrics* memory_metrics) const;
530
531   bool NeedsToRecordFirstActivePaint(int metric_type) const;
532
533   // Sets the current pipeline rendering color space.
534   void SetRenderingColorSpace(const gfx::ColorSpace& color_space);
535
536  protected:
537   RenderThreadImpl(
538       const InProcessChildThreadParams& params,
539       std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler,
540       const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
541       base::MessageLoop* unowned_message_loop);
542   RenderThreadImpl(
543       std::unique_ptr<base::MessageLoop> main_message_loop,
544       std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler);
545
546  private:
547   void OnProcessFinalRelease() override;
548   // IPC::Listener
549   void OnChannelError() override;
550
551   // ChildThread
552   bool OnControlMessageReceived(const IPC::Message& msg) override;
553   void RecordAction(const base::UserMetricsAction& action) override;
554   void RecordComputedAction(const std::string& action) override;
555
556   bool IsMainThread();
557
558   // base::MemoryCoordinatorClient implementation:
559   void OnMemoryStateChange(base::MemoryState state) override;
560   void OnPurgeMemory() override;
561
562   void RecordPurgeMemory(RendererMemoryMetrics before);
563
564   void Init(
565       const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue);
566
567   void InitializeCompositorThread();
568
569   void InitializeWebKit(
570       const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
571       service_manager::BinderRegistry* registry);
572
573   void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
574   void OnGetAccessibilityTree();
575
576   // mojom::Renderer:
577   void CreateEmbedderRendererService(
578       service_manager::mojom::ServiceRequest service_request) override;
579   void CreateView(mojom::CreateViewParamsPtr params) override;
580   void CreateFrame(mojom::CreateFrameParamsPtr params) override;
581   void SetUpEmbeddedWorkerChannelForServiceWorker(
582       mojom::EmbeddedWorkerInstanceClientAssociatedRequest client_request)
583       override;
584   void CreateFrameProxy(
585       int32_t routing_id,
586       int32_t render_view_routing_id,
587       int32_t opener_routing_id,
588       int32_t parent_routing_id,
589       const FrameReplicationState& replicated_state,
590       const base::UnguessableToken& devtools_frame_token) override;
591   void OnNetworkConnectionChanged(
592       net::NetworkChangeNotifier::ConnectionType type,
593       double max_bandwidth_mbps) override;
594   void OnNetworkQualityChanged(net::EffectiveConnectionType type,
595                                base::TimeDelta http_rtt,
596                                base::TimeDelta transport_rtt,
597                                double bandwidth_kbps) override;
598   void SetWebKitSharedTimersSuspended(bool suspend) override;
599   void UpdateScrollbarTheme(
600       mojom::UpdateScrollbarThemeParamsPtr params) override;
601   void OnSystemColorsChanged(int32_t aqua_color_variant,
602                              const std::string& highlight_text_color,
603                              const std::string& highlight_color) override;
604   void PurgePluginListCache(bool reload_pages) override;
605   void SetProcessBackgrounded(bool backgrounded) override;
606   void SetSchedulerKeepActive(bool keep_active) override;
607   void ProcessPurgeAndSuspend() override;
608
609   void OnMemoryPressure(
610       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
611
612   bool RendererIsHidden() const;
613   void OnRendererHidden();
614   void OnRendererVisible();
615
616   void RecordMemoryUsageAfterBackgrounded(const char* suffix,
617                                           int foregrounded_count);
618   void RecordPurgeAndSuspendMemoryGrowthMetrics(
619       const char* suffix,
620       int foregrounded_count_when_purged);
621
622   void ReleaseFreeMemory();
623
624   void OnSyncMemoryPressure(
625       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
626
627   std::unique_ptr<viz::SyntheticBeginFrameSource>
628   CreateSyntheticBeginFrameSource();
629
630   void OnRendererInterfaceRequest(mojom::RendererAssociatedRequest request);
631
632   std::unique_ptr<discardable_memory::ClientDiscardableSharedMemoryManager>
633       discardable_shared_memory_manager_;
634
635   // These objects live solely on the render thread.
636   std::unique_ptr<AppCacheDispatcher> appcache_dispatcher_;
637   std::unique_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
638   std::unique_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
639   std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
640       main_thread_scheduler_;
641   std::unique_ptr<RendererBlinkPlatformImpl> blink_platform_impl_;
642   std::unique_ptr<ResourceDispatcher> resource_dispatcher_;
643   std::unique_ptr<FileSystemDispatcher> file_system_dispatcher_;
644   std::unique_ptr<URLLoaderThrottleProvider> url_loader_throttle_provider_;
645
646   // Used on the renderer and IPC threads.
647   scoped_refptr<MidiMessageFilter> midi_message_filter_;
648   scoped_refptr<ServiceWorkerMessageFilter> service_worker_message_filter_;
649
650   std::unique_ptr<BrowserPluginManager> browser_plugin_manager_;
651
652 #if BUILDFLAG(ENABLE_WEBRTC)
653   std::unique_ptr<PeerConnectionDependencyFactory> peer_connection_factory_;
654
655   // This is used to communicate to the browser process the status
656   // of all the peer connections created in the renderer.
657   std::unique_ptr<PeerConnectionTracker> peer_connection_tracker_;
658
659   // Dispatches all P2P sockets.
660   scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
661
662   // Used for communicating registering AEC dump consumers with the browser and
663   // receving AEC dump file handles when AEC dump is enabled. An AEC dump is
664   // diagnostic audio data for WebRTC stored locally when enabled by the user in
665   // chrome://webrtc-internals.
666   scoped_refptr<AecDumpMessageFilter> aec_dump_message_filter_;
667 #endif
668
669   // Provides AudioInputIPC objects for audio input devices. Initialized in
670   // Init.
671   base::Optional<AudioInputIPCFactory> audio_input_ipc_factory_;
672   // Provides AudioOutputIPC objects for audio output devices. It either uses
673   // an AudioMessageFilter for this or provides MojoAudioOutputIPC objects.
674   // Initialized in Init.
675   base::Optional<AudioOutputIPCFactory> audio_output_ipc_factory_;
676
677   // Used on the render thread.
678   std::unique_ptr<VideoCaptureImplManager> vc_manager_;
679
680   std::unique_ptr<viz::ClientSharedBitmapManager> shared_bitmap_manager_;
681
682   scoped_refptr<NotificationDispatcher> notification_dispatcher_;
683
684   // The time Blink was initialized. Used for UMA.
685   base::TimeTicks blink_initialized_time_;
686
687   // The count of RenderWidgets running through this thread.
688   int widget_count_;
689
690   // The count of hidden RenderWidgets running through this thread.
691   int hidden_widget_count_;
692
693   // The current value of the idle notification timer delay.
694   int64_t idle_notification_delay_in_ms_;
695
696   // The number of idle handler calls that skip sending idle notifications.
697   int idle_notifications_to_skip_;
698
699   bool webkit_shared_timer_suspended_;
700
701   // Used to control layout test specific behavior.
702   std::unique_ptr<LayoutTestDependencies> layout_test_deps_;
703
704   // Timer that periodically calls IdleHandler.
705   base::RepeatingTimer idle_timer_;
706
707   // Sticky once true, indicates that compositing is done without Gpu, so
708   // resources given to the compositor or to the viz service should be
709   // software-based.
710   bool is_gpu_compositing_disabled_ = false;
711
712   // The message loop of the renderer main thread.
713   // This message loop should be destructed before the RenderThreadImpl
714   // shuts down Blink.
715   // Some test users (e.g. InProcessRenderThread) own the MessageLoop used by
716   // their RenderThreadImpls. |main_message_loop_| is always non-nulll,
717   // |owned_message_loop_| is non-null if handed in at creation.
718   const std::unique_ptr<base::MessageLoop> owned_message_loop_;
719   base::MessageLoop* const main_message_loop_;
720
721   // May be null if overridden by ContentRendererClient.
722   std::unique_ptr<blink::scheduler::WebThreadBase> compositor_thread_;
723
724   // Utility class to provide GPU functionalities to media.
725   // TODO(dcastagna): This should be just one scoped_ptr once
726   // http://crbug.com/580386 is fixed.
727   // NOTE(dcastagna): At worst this accumulates a few bytes per context lost.
728   std::vector<std::unique_ptr<GpuVideoAcceleratorFactoriesImpl>> gpu_factories_;
729
730   // Thread for running multimedia operations (e.g., video decoding).
731   std::unique_ptr<base::Thread> media_thread_;
732
733   // Will point to appropriate task runner after initialization,
734   // regardless of whether |compositor_thread_| is overriden.
735   scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_;
736
737   // Pool of workers used for raster operations (e.g., tile rasterization).
738   scoped_refptr<CategorizedWorkerPool> categorized_worker_pool_;
739
740   base::CancelableCallback<void(const IPC::Message&)> main_input_callback_;
741   scoped_refptr<IPC::MessageFilter> input_event_filter_;
742   std::unique_ptr<InputHandlerManager> input_handler_manager_;
743
744 #if defined(OS_ANDROID)
745   scoped_refptr<SynchronousCompositorFilter> sync_compositor_message_filter_;
746   scoped_refptr<StreamTextureFactory> stream_texture_factory_;
747 #endif
748
749   scoped_refptr<ui::ContextProviderCommandBuffer> shared_main_thread_contexts_;
750
751   base::ObserverList<RenderThreadObserver> observers_;
752
753   scoped_refptr<viz::RasterContextProvider> shared_worker_context_provider_;
754
755   std::unique_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
756
757   HistogramCustomizer histogram_customizer_;
758
759   std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
760
761   std::unique_ptr<ChildMemoryCoordinatorImpl> memory_coordinator_;
762
763   std::unique_ptr<ui::Gpu> gpu_;
764
765   scoped_refptr<base::SingleThreadTaskRunner>
766       main_thread_compositor_task_runner_;
767
768   // Compositor settings.
769   bool is_gpu_rasterization_forced_;
770   int gpu_rasterization_msaa_sample_count_;
771   bool is_lcd_text_enabled_;
772   bool is_zero_copy_enabled_;
773   bool is_gpu_memory_buffer_compositor_resources_enabled_;
774   bool is_partial_raster_enabled_;
775   bool is_elastic_overscroll_enabled_;
776   bool is_threaded_animation_enabled_;
777   bool is_scroll_animator_enabled_;
778
779   // Target rendering ColorSpace.
780   gfx::ColorSpace rendering_color_space_;
781
782   class PendingFrameCreate : public base::RefCounted<PendingFrameCreate> {
783    public:
784     PendingFrameCreate(const service_manager::BindSourceInfo& source_info,
785                        int routing_id,
786                        mojom::FrameRequest frame_request);
787
788     const service_manager::BindSourceInfo& browser_info() const {
789       return browser_info_;
790     }
791     mojom::FrameRequest TakeFrameRequest() { return std::move(frame_request_); }
792
793    private:
794     friend class base::RefCounted<PendingFrameCreate>;
795
796     ~PendingFrameCreate();
797
798     // Mojo error handler.
799     void OnConnectionError();
800
801     service_manager::BindSourceInfo browser_info_;
802     int routing_id_;
803     mojom::FrameRequest frame_request_;
804   };
805
806   using PendingFrameCreateMap =
807       std::map<int, scoped_refptr<PendingFrameCreate>>;
808   PendingFrameCreateMap pending_frame_creates_;
809
810   mojom::StoragePartitionServicePtr storage_partition_service_;
811   mojom::RendererHostAssociatedPtr renderer_host_;
812
813   AssociatedInterfaceRegistryImpl associated_interfaces_;
814
815   mojo::AssociatedBinding<mojom::Renderer> renderer_binding_;
816
817   mojom::RenderFrameMessageFilterAssociatedPtr render_frame_message_filter_;
818   mojom::RenderMessageFilterAssociatedPtr render_message_filter_;
819
820   RendererMemoryMetrics purge_and_suspend_memory_metrics_;
821   bool needs_to_record_first_active_paint_;
822   base::TimeTicks was_backgrounded_time_;
823   int process_foregrounded_count_;
824
825   int32_t client_id_;
826
827   mojom::FrameSinkProviderPtr frame_sink_provider_;
828
829   // A mojo connection to the CompositingModeReporter service.
830   viz::mojom::CompositingModeReporterPtr compositing_mode_reporter_;
831   // The class is a CompositingModeWatcher, which is bound to mojo through
832   // this member.
833   mojo::Binding<viz::mojom::CompositingModeWatcher>
834       compositing_mode_watcher_binding_;
835
836   base::WeakPtrFactory<RenderThreadImpl> weak_factory_;
837
838   DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
839 };
840
841 #if defined(COMPILER_MSVC)
842 #pragma warning(pop)
843 #endif
844
845 }  // namespace content
846
847 #endif  // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_