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.
5 #include "content/renderer/render_thread_impl.h"
12 #include "base/allocator/allocator_extension.h"
13 #include "base/command_line.h"
14 #include "base/lazy_instance.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/memory/discardable_memory_allocator.h"
18 #include "base/memory/shared_memory.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_tokenizer.h"
26 #include "base/strings/sys_string_conversions.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/thread_task_runner_handle.h"
29 #include "base/threading/simple_thread.h"
30 #include "base/threading/thread_local.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/trace_event/memory_dump_manager.h"
33 #include "base/trace_event/trace_event.h"
34 #include "base/values.h"
35 #include "cc/base/histograms.h"
36 #include "cc/base/switches.h"
37 #include "cc/blink/web_external_bitmap_impl.h"
38 #include "cc/blink/web_layer_impl.h"
39 #include "cc/raster/task_graph_runner.h"
40 #include "cc/trees/layer_tree_settings.h"
41 #include "components/scheduler/renderer/renderer_scheduler.h"
42 #include "content/child/appcache/appcache_dispatcher.h"
43 #include "content/child/appcache/appcache_frontend_impl.h"
44 #include "content/child/child_discardable_shared_memory_manager.h"
45 #include "content/child/child_gpu_memory_buffer_manager.h"
46 #include "content/child/child_histogram_message_filter.h"
47 #include "content/child/child_resource_message_filter.h"
48 #include "content/child/child_shared_bitmap_manager.h"
49 #include "content/child/content_child_helpers.h"
50 #include "content/child/db_message_filter.h"
51 #include "content/child/indexed_db/indexed_db_dispatcher.h"
52 #include "content/child/indexed_db/indexed_db_message_filter.h"
53 #include "content/child/npapi/npobject_util.h"
54 #include "content/child/plugin_messages.h"
55 #include "content/child/resource_dispatcher.h"
56 #include "content/child/resource_scheduling_filter.h"
57 #include "content/child/runtime_features.h"
58 #include "content/child/thread_safe_sender.h"
59 #include "content/child/web_database_observer_impl.h"
60 #include "content/child/worker_task_runner.h"
61 #include "content/common/child_process_messages.h"
62 #include "content/common/content_constants_internal.h"
63 #include "content/common/database_messages.h"
64 #include "content/common/dom_storage/dom_storage_messages.h"
65 #include "content/common/frame_messages.h"
66 #include "content/common/gpu/client/context_provider_command_buffer.h"
67 #include "content/common/gpu/client/gpu_channel_host.h"
68 #include "content/common/gpu/gpu_messages.h"
69 #include "content/common/gpu/gpu_process_launch_causes.h"
70 #include "content/common/render_frame_setup.mojom.h"
71 #include "content/common/render_process_messages.h"
72 #include "content/common/resource_messages.h"
73 #include "content/common/service_worker/embedded_worker_setup.mojom.h"
74 #include "content/common/view_messages.h"
75 #include "content/common/worker_messages.h"
76 #include "content/public/common/content_constants.h"
77 #include "content/public/common/content_paths.h"
78 #include "content/public/common/content_switches.h"
79 #include "content/public/common/mojo_channel_switches.h"
80 #include "content/public/common/renderer_preferences.h"
81 #include "content/public/common/url_constants.h"
82 #include "content/public/renderer/content_renderer_client.h"
83 #include "content/public/renderer/render_process_observer.h"
84 #include "content/public/renderer/render_view_visitor.h"
85 #include "content/renderer/bluetooth/bluetooth_message_filter.h"
86 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
87 #include "content/renderer/cache_storage/cache_storage_dispatcher.h"
88 #include "content/renderer/cache_storage/cache_storage_message_filter.h"
89 #include "content/renderer/devtools/devtools_agent_filter.h"
90 #include "content/renderer/devtools/v8_sampling_profiler.h"
91 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
92 #include "content/renderer/dom_storage/webstoragearea_impl.h"
93 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
94 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
95 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
96 #include "content/renderer/gpu/compositor_output_surface.h"
97 #include "content/renderer/input/input_event_filter.h"
98 #include "content/renderer/input/input_handler_manager.h"
99 #include "content/renderer/input/main_thread_input_event_filter.h"
100 #include "content/renderer/media/aec_dump_message_filter.h"
101 #include "content/renderer/media/audio_input_message_filter.h"
102 #include "content/renderer/media/audio_message_filter.h"
103 #include "content/renderer/media/audio_renderer_mixer_manager.h"
104 #include "content/renderer/media/media_stream_center.h"
105 #include "content/renderer/media/midi_message_filter.h"
106 #include "content/renderer/media/render_media_client.h"
107 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
108 #include "content/renderer/media/video_capture_impl_manager.h"
109 #include "content/renderer/media/video_capture_message_filter.h"
110 #include "content/renderer/net_info_helper.h"
111 #include "content/renderer/p2p/socket_dispatcher.h"
112 #include "content/renderer/raster_worker_pool.h"
113 #include "content/renderer/render_frame_proxy.h"
114 #include "content/renderer/render_process_impl.h"
115 #include "content/renderer/render_view_impl.h"
116 #include "content/renderer/renderer_blink_platform_impl.h"
117 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
118 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
119 #include "content/renderer/service_worker/service_worker_context_client.h"
120 #include "content/renderer/service_worker/service_worker_context_message_filter.h"
121 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
122 #include "gin/public/debug.h"
123 #include "gpu/GLES2/gl2extchromium.h"
124 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
125 #include "ipc/ipc_channel_handle.h"
126 #include "ipc/ipc_platform_file.h"
127 #include "ipc/mojo/ipc_channel_mojo.h"
128 #include "media/base/audio_hardware_config.h"
129 #include "media/base/media.h"
130 #include "media/renderers/gpu_video_accelerator_factories.h"
131 #include "mojo/common/common_type_converters.h"
132 #include "net/base/net_errors.h"
133 #include "net/base/port_util.h"
134 #include "skia/ext/event_tracer_impl.h"
135 #include "skia/ext/skia_memory_dump_provider.h"
136 #include "third_party/WebKit/public/platform/WebImageGenerator.h"
137 #include "third_party/WebKit/public/platform/WebString.h"
138 #include "third_party/WebKit/public/platform/WebThread.h"
139 #include "third_party/WebKit/public/web/WebCache.h"
140 #include "third_party/WebKit/public/web/WebColorName.h"
141 #include "third_party/WebKit/public/web/WebDatabase.h"
142 #include "third_party/WebKit/public/web/WebDocument.h"
143 #include "third_party/WebKit/public/web/WebFrame.h"
144 #include "third_party/WebKit/public/web/WebImageCache.h"
145 #include "third_party/WebKit/public/web/WebKit.h"
146 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
147 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
148 #include "third_party/WebKit/public/web/WebScriptController.h"
149 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
150 #include "third_party/WebKit/public/web/WebView.h"
151 #include "third_party/icu/source/i18n/unicode/timezone.h"
152 #include "third_party/mojo/src/mojo/public/cpp/bindings/strong_binding.h"
153 #include "third_party/skia/include/core/SkGraphics.h"
154 #include "ui/base/layout.h"
155 #include "ui/base/ui_base_switches.h"
156 #include "v8/include/v8.h"
158 #if defined(OS_ANDROID)
159 #include <cpu-features.h>
160 #include "content/renderer/android/synchronous_compositor_factory.h"
161 #include "content/renderer/media/android/renderer_demuxer_android.h"
164 #if defined(OS_MACOSX)
165 #include "base/mac/mac_util.h"
166 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
169 #if defined(OS_POSIX)
170 #include "ipc/ipc_channel_posix.h"
178 #include "content/child/npapi/np_channel_base.h"
181 #if defined(ENABLE_PLUGINS)
182 #include "content/renderer/npapi/plugin_channel_host.h"
185 #if defined(ENABLE_WEBRTC)
186 #include "content/renderer/media/peer_connection_tracker.h"
187 #include "content/renderer/media/rtc_peer_connection_handler.h"
188 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
189 #include "content/renderer/media/webrtc_identity_service.h"
192 #ifdef ENABLE_VTUNE_JIT_INTERFACE
193 #include "v8/src/third_party/vtune/v8-vtune.h"
196 using base::ThreadRestrictions
;
197 using blink::WebDocument
;
198 using blink::WebFrame
;
199 using blink::WebNetworkStateNotifier
;
200 using blink::WebRuntimeFeatures
;
201 using blink::WebScriptController
;
202 using blink::WebSecurityPolicy
;
203 using blink::WebString
;
204 using blink::WebView
;
210 const int64 kInitialIdleHandlerDelayMs
= 1000;
211 const int64 kLongIdleHandlerDelayMs
= 30*1000;
213 #if defined(OS_ANDROID)
214 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
215 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
216 // induced work takes but a fraction (~1/4) of the overall frame budget.
217 const int kMaxResourceRequestsPerFlushWhenThrottled
= 3;
219 const int kMaxResourceRequestsPerFlushWhenThrottled
= 8;
221 const double kThrottledResourceRequestFlushPeriodS
= 1. / 60.;
223 // Maximum allocation size allowed for image scaling filters that
224 // require pre-scaling. Skia will fallback to a filter that doesn't
225 // require pre-scaling if the default filter would require an
226 // allocation that exceeds this limit.
227 const size_t kImageCacheSingleAllocationByteLimit
= 64 * 1024 * 1024;
229 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
230 // incorrectly from the wrong thread.
231 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
232 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
234 class RenderViewZoomer
: public RenderViewVisitor
{
236 RenderViewZoomer(const std::string
& scheme
,
237 const std::string
& host
,
238 double zoom_level
) : scheme_(scheme
),
240 zoom_level_(zoom_level
) {
243 bool Visit(RenderView
* render_view
) override
{
244 WebView
* webview
= render_view
->GetWebView();
245 RenderViewImpl
* render_view_impl
=
246 static_cast<RenderViewImpl
*>(render_view
);
247 // Remote frames don't host documents.
248 // TODO(wjmaclean) Although it seems likely that a frame without a
249 // document can safely early-out here, we should confirm this is truly
250 // the case. https://crbug.com/477007
251 if (webview
->mainFrame()->isWebRemoteFrame())
254 WebDocument document
= webview
->mainFrame()->document();
256 // Don't set zoom level for full-page plugin since they don't use the same
258 if (document
.isPluginDocument())
260 GURL
url(document
.url());
261 // Empty scheme works as wildcard that matches any scheme,
262 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
263 (scheme_
.empty() || scheme_
== url
.scheme()) &&
264 !render_view_impl
->uses_temporary_zoom_level()) {
265 webview
->hidePopups();
266 render_view_impl
->SetZoomLevel(zoom_level_
);
272 const std::string scheme_
;
273 const std::string host_
;
274 const double zoom_level_
;
276 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
279 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
280 if (host
== "mail.google.com")
282 if (host
== "docs.google.com" || host
== "drive.google.com")
284 if (host
== "plus.google.com")
286 if (host
== "inbox.google.com")
288 return std::string();
291 void* CreateHistogram(
292 const char *name
, int min
, int max
, size_t buckets
) {
295 std::string histogram_name
;
296 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
297 if (render_thread_impl
) { // Can be null in tests.
298 histogram_name
= render_thread_impl
->
299 histogram_customizer()->ConvertToCustomHistogramName(name
);
301 histogram_name
= std::string(name
);
303 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
304 histogram_name
, min
, max
, buckets
,
305 base::Histogram::kUmaTargetedHistogramFlag
);
309 void AddHistogramSample(void* hist
, int sample
) {
310 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
311 histogram
->Add(sample
);
314 scoped_ptr
<cc::SharedBitmap
> AllocateSharedBitmapFunction(
315 const gfx::Size
& size
) {
316 return ChildThreadImpl::current()->shared_bitmap_manager()->
317 AllocateSharedBitmap(size
);
320 void EnableBlinkPlatformLogChannels(const std::string
& channels
) {
321 if (channels
.empty())
323 base::StringTokenizer
t(channels
, ", ");
325 blink::enableLogChannel(t
.token().c_str());
328 void NotifyTimezoneChangeOnThisThread() {
329 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
332 v8::Date::DateTimeConfigurationChangeNotification(isolate
);
335 void LowMemoryNotificationOnThisThread() {
336 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
339 isolate
->LowMemoryNotification();
342 class RenderFrameSetupImpl
: public RenderFrameSetup
{
344 explicit RenderFrameSetupImpl(
345 mojo::InterfaceRequest
<RenderFrameSetup
> request
)
346 : routing_id_highmark_(-1), binding_(this, request
.Pass()) {}
348 void ExchangeServiceProviders(
349 int32_t frame_routing_id
,
350 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
351 mojo::ServiceProviderPtr exposed_services
)
353 // TODO(morrita): This is for investigating http://crbug.com/415059 and
354 // should be removed once it is fixed.
355 CHECK_LT(routing_id_highmark_
, frame_routing_id
);
356 routing_id_highmark_
= frame_routing_id
;
358 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(frame_routing_id
);
359 // We can receive a GetServiceProviderForFrame message for a frame not yet
360 // created due to a race between the message and a ViewMsg_New IPC that
361 // triggers creation of the RenderFrame we want.
363 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
364 frame_routing_id
, services
.Pass(), exposed_services
.Pass());
368 frame
->BindServiceRegistry(services
.Pass(), exposed_services
.Pass());
372 int32_t routing_id_highmark_
;
373 mojo::StrongBinding
<RenderFrameSetup
> binding_
;
376 void CreateRenderFrameSetup(mojo::InterfaceRequest
<RenderFrameSetup
> request
) {
377 new RenderFrameSetupImpl(request
.Pass());
380 blink::WebGraphicsContext3D::Attributes
GetOffscreenAttribs() {
381 blink::WebGraphicsContext3D::Attributes attributes
;
382 attributes
.shareResources
= true;
383 attributes
.depth
= false;
384 attributes
.stencil
= false;
385 attributes
.antialias
= false;
386 attributes
.noAutomaticFlushes
= true;
390 void SetupEmbeddedWorkerOnWorkerThread(
391 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
392 mojo::ServiceProviderPtr exposed_services
) {
393 ServiceWorkerContextClient
* client
=
394 ServiceWorkerContextClient::ThreadSpecificInstance();
395 // It is possible for client to be null if for some reason the worker died
396 // before this call made it to the worker thread. In that case just do
397 // nothing and let mojo close the connection.
400 client
->BindServiceRegistry(services
.Pass(), exposed_services
.Pass());
403 class EmbeddedWorkerSetupImpl
: public EmbeddedWorkerSetup
{
405 explicit EmbeddedWorkerSetupImpl(
406 mojo::InterfaceRequest
<EmbeddedWorkerSetup
> request
)
407 : binding_(this, request
.Pass()) {}
409 void ExchangeServiceProviders(
411 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
412 mojo::ServiceProviderPtr exposed_services
) override
{
413 WorkerTaskRunner::Instance()->GetTaskRunnerFor(thread_id
)->PostTask(
415 base::Bind(&SetupEmbeddedWorkerOnWorkerThread
, base::Passed(&services
),
416 base::Passed(&exposed_services
)));
420 mojo::StrongBinding
<EmbeddedWorkerSetup
> binding_
;
423 void CreateEmbeddedWorkerSetup(
424 mojo::InterfaceRequest
<EmbeddedWorkerSetup
> request
) {
425 new EmbeddedWorkerSetupImpl(request
.Pass());
428 void StringToUintVector(const std::string
& str
, std::vector
<unsigned>* vector
) {
429 DCHECK(vector
->empty());
430 std::vector
<std::string
> pieces
= base::SplitString(
431 str
, ",", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
432 DCHECK_EQ(pieces
.size(), static_cast<size_t>(gfx::BufferFormat::LAST
) + 1);
433 for (size_t i
= 0; i
< pieces
.size(); ++i
) {
435 bool succeed
= base::StringToUint(pieces
[i
], &number
);
437 vector
->push_back(number
);
443 // For measuring memory usage after each task. Behind a command line flag.
444 class MemoryObserver
: public base::MessageLoop::TaskObserver
{
447 ~MemoryObserver() override
{}
449 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
451 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
452 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
456 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
459 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
460 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
461 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
462 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
465 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
467 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
468 const std::string
& host
, size_t view_count
) {
469 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
470 switches::kDisableHistogramCustomizer
)) {
473 // Check if all RenderViews are displaying a page from the same host. If there
474 // is only one RenderView, the common host is this view's host. If there are
475 // many, check if this one shares the common host of the other
476 // RenderViews. It's ok to not detect some cases where the RenderViews share a
477 // common host. This information is only used for producing custom histograms.
480 else if (host
!= common_host_
)
481 SetCommonHost(std::string());
484 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
485 const char* histogram_name
) const {
486 std::string
name(histogram_name
);
487 if (!common_host_histogram_suffix_
.empty() &&
488 custom_histograms_
.find(name
) != custom_histograms_
.end())
489 name
+= common_host_histogram_suffix_
;
493 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
494 const std::string
& host
) {
495 if (host
!= common_host_
) {
497 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
498 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram
);
503 RenderThreadImpl
* RenderThreadImpl::Create(
504 const InProcessChildThreadParams
& params
) {
505 scoped_ptr
<scheduler::RendererScheduler
> renderer_scheduler
=
506 scheduler::RendererScheduler::Create();
507 return new RenderThreadImpl(params
, renderer_scheduler
.Pass());
511 RenderThreadImpl
* RenderThreadImpl::Create(
512 scoped_ptr
<base::MessageLoop
> main_message_loop
,
513 scoped_ptr
<scheduler::RendererScheduler
> renderer_scheduler
) {
514 return new RenderThreadImpl(main_message_loop
.Pass(),
515 renderer_scheduler
.Pass());
518 RenderThreadImpl
* RenderThreadImpl::current() {
519 return lazy_tls
.Pointer()->Get();
522 RenderThreadImpl::RenderThreadImpl(
523 const InProcessChildThreadParams
& params
,
524 scoped_ptr
<scheduler::RendererScheduler
> scheduler
)
525 : ChildThreadImpl(Options::Builder()
526 .InBrowserProcess(params
)
527 .UseMojoChannel(ShouldUseMojoChannel())
529 renderer_scheduler_(scheduler
.Pass()),
530 raster_worker_pool_(new RasterWorkerPool()) {
534 // When we run plugins in process, we actually run them on the render thread,
535 // which means that we need to make the render thread pump UI events.
536 RenderThreadImpl::RenderThreadImpl(
537 scoped_ptr
<base::MessageLoop
> main_message_loop
,
538 scoped_ptr
<scheduler::RendererScheduler
> scheduler
)
539 : ChildThreadImpl(Options::Builder()
540 .UseMojoChannel(ShouldUseMojoChannel())
542 renderer_scheduler_(scheduler
.Pass()),
543 main_message_loop_(main_message_loop
.Pass()),
544 raster_worker_pool_(new RasterWorkerPool()) {
548 void RenderThreadImpl::Init() {
549 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
551 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
552 base::PlatformThread::CurrentId(),
553 kTraceEventRendererMainThreadSortIndex
);
555 #if defined(OS_MACOSX) || defined(OS_ANDROID)
556 // On Mac and Android, the select popups are rendered by the browser.
557 blink::WebView::setUseExternalPopupMenus(true);
560 lazy_tls
.Pointer()->Set(this);
562 // Register this object as the main thread.
563 ChildProcess::current()->set_main_thread(this);
565 // In single process the single process is all there is.
566 notify_webkit_of_modal_loop_
= true;
567 webkit_shared_timer_suspended_
= false;
569 hidden_widget_count_
= 0;
570 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
571 idle_notifications_to_skip_
= 0;
572 layout_test_mode_
= false;
574 appcache_dispatcher_
.reset(
575 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
576 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
577 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
578 thread_safe_sender()));
579 main_thread_cache_storage_dispatcher_
.reset(
580 new CacheStorageDispatcher(thread_safe_sender()));
581 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
583 // Note: This may reorder messages from the ResourceDispatcher with respect to
585 resource_dispatch_throttler_
.reset(new ResourceDispatchThrottler(
586 static_cast<RenderThread
*>(this), renderer_scheduler_
.get(),
587 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS
),
588 kMaxResourceRequestsPerFlushWhenThrottled
));
589 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_
.get());
591 media_stream_center_
= NULL
;
593 db_message_filter_
= new DBMessageFilter();
594 AddFilter(db_message_filter_
.get());
596 vc_manager_
.reset(new VideoCaptureImplManager());
597 AddFilter(vc_manager_
->video_capture_message_filter());
599 browser_plugin_manager_
.reset(new BrowserPluginManager());
600 AddObserver(browser_plugin_manager_
.get());
602 #if defined(ENABLE_WEBRTC)
603 peer_connection_tracker_
.reset(new PeerConnectionTracker());
604 AddObserver(peer_connection_tracker_
.get());
606 p2p_socket_dispatcher_
=
607 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
608 AddFilter(p2p_socket_dispatcher_
.get());
610 webrtc_identity_service_
.reset(new WebRTCIdentityService());
612 aec_dump_message_filter_
= new AecDumpMessageFilter(
613 GetIOMessageLoopProxy(), message_loop()->task_runner());
614 AddFilter(aec_dump_message_filter_
.get());
616 peer_connection_factory_
.reset(new PeerConnectionDependencyFactory(
617 p2p_socket_dispatcher_
.get()));
618 #endif // defined(ENABLE_WEBRTC)
620 audio_input_message_filter_
=
621 new AudioInputMessageFilter(GetIOMessageLoopProxy());
622 AddFilter(audio_input_message_filter_
.get());
624 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
625 AddFilter(audio_message_filter_
.get());
627 midi_message_filter_
= new MidiMessageFilter(GetIOMessageLoopProxy());
628 AddFilter(midi_message_filter_
.get());
630 bluetooth_message_filter_
= new BluetoothMessageFilter(thread_safe_sender());
631 AddFilter(bluetooth_message_filter_
->GetFilter());
633 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
635 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
637 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
639 GetContentClient()->renderer()->RenderThreadStarted();
641 InitSkiaEventTracer();
642 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
643 skia::SkiaMemoryDumpProvider::GetInstance());
645 const base::CommandLine
& command_line
=
646 *base::CommandLine::ForCurrentProcess();
648 cc::LayerSettings layer_settings
;
649 if (command_line
.HasSwitch(switches::kEnableCompositorAnimationTimelines
))
650 layer_settings
.use_compositor_animation_timelines
= true;
651 cc_blink::WebLayerImpl::SetLayerSettings(layer_settings
);
652 cc::SetClientNameForMetrics("Renderer");
654 is_threaded_animation_enabled_
=
655 !command_line
.HasSwitch(cc::switches::kDisableThreadedAnimation
);
657 is_zero_copy_enabled_
= command_line
.HasSwitch(switches::kEnableZeroCopy
);
658 is_persistent_gpu_memory_buffer_enabled_
=
659 command_line
.HasSwitch(switches::kEnablePersistentGpuMemoryBuffer
);
661 #if defined(OS_MACOSX) && !defined(OS_IOS)
662 is_elastic_overscroll_enabled_
= base::mac::IsOSLionOrLater();
663 if (is_elastic_overscroll_enabled_
) {
664 base::ScopedCFTypeRef
<CFStringRef
> key(
665 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
666 Boolean key_exists
= false;
667 Boolean value
= CFPreferencesGetAppBooleanValue(
668 key
, kCFPreferencesCurrentApplication
, &key_exists
);
669 if (key_exists
&& !value
)
670 is_elastic_overscroll_enabled_
= false;
673 is_elastic_overscroll_enabled_
= false;
676 std::string image_texture_target_string
=
677 command_line
.GetSwitchValueASCII(switches::kContentImageTextureTarget
);
678 StringToUintVector(image_texture_target_string
, &use_image_texture_targets_
);
680 if (command_line
.HasSwitch(switches::kDisableLCDText
)) {
681 is_lcd_text_enabled_
= false;
682 } else if (command_line
.HasSwitch(switches::kEnableLCDText
)) {
683 is_lcd_text_enabled_
= true;
685 #if defined(OS_ANDROID)
686 is_lcd_text_enabled_
= false;
688 is_lcd_text_enabled_
= true;
692 is_gpu_rasterization_enabled_
=
693 command_line
.HasSwitch(switches::kEnableGpuRasterization
);
694 is_gpu_rasterization_forced_
=
695 command_line
.HasSwitch(switches::kForceGpuRasterization
);
697 if (command_line
.HasSwitch(switches::kGpuRasterizationMSAASampleCount
)) {
698 std::string string_value
= command_line
.GetSwitchValueASCII(
699 switches::kGpuRasterizationMSAASampleCount
);
700 bool parsed_msaa_sample_count
=
701 base::StringToInt(string_value
, &gpu_rasterization_msaa_sample_count_
);
702 DCHECK(parsed_msaa_sample_count
) << string_value
;
703 DCHECK_GE(gpu_rasterization_msaa_sample_count_
, 0);
705 gpu_rasterization_msaa_sample_count_
= -1;
708 if (command_line
.HasSwitch(switches::kDisableDistanceFieldText
)) {
709 is_distance_field_text_enabled_
= false;
710 } else if (command_line
.HasSwitch(switches::kEnableDistanceFieldText
)) {
711 is_distance_field_text_enabled_
= true;
713 is_distance_field_text_enabled_
= false;
716 // Note that under Linux, the media library will normally already have
717 // been initialized by the Zygote before this instance became a Renderer.
718 media::InitializeMediaLibrary();
720 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
721 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
723 is_gather_pixel_refs_enabled_
= false;
725 int num_raster_threads
= 0;
726 std::string string_value
=
727 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
728 bool parsed_num_raster_threads
=
729 base::StringToInt(string_value
, &num_raster_threads
);
730 DCHECK(parsed_num_raster_threads
) << string_value
;
731 DCHECK_GT(num_raster_threads
, 0);
733 // Note: Currently, gathering of pixel refs when using a single
734 // raster thread doesn't provide any benefit. This might change
735 // in the future but we avoid it for now to reduce the cost of
737 is_gather_pixel_refs_enabled_
= num_raster_threads
> 1;
739 base::SimpleThread::Options thread_options
;
740 #if defined(OS_ANDROID) || defined(OS_LINUX)
741 if (!command_line
.HasSwitch(
742 switches::kUseNormalPriorityForTileTaskWorkerThreads
)) {
743 thread_options
.set_priority(base::ThreadPriority::BACKGROUND
);
747 raster_worker_pool_
->Start(num_raster_threads
, thread_options
);
749 // TODO(boliu): In single process, browser main loop should set up the
750 // discardable memory manager, and should skip this if kSingleProcess.
751 // See crbug.com/503724.
752 base::DiscardableMemoryAllocator::SetInstance(
753 ChildThreadImpl::discardable_shared_memory_manager());
755 service_registry()->AddService
<RenderFrameSetup
>(
756 base::Bind(CreateRenderFrameSetup
));
757 service_registry()->AddService
<EmbeddedWorkerSetup
>(
758 base::Bind(CreateEmbeddedWorkerSetup
));
760 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
763 RenderThreadImpl::~RenderThreadImpl() {
766 void RenderThreadImpl::Shutdown() {
768 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
770 ChildThreadImpl::Shutdown();
772 if (memory_observer_
) {
773 message_loop()->RemoveTaskObserver(memory_observer_
.get());
774 memory_observer_
.reset();
777 // Wait for all databases to be closed.
778 if (blink_platform_impl_
) {
779 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
780 // processing timer events while we're already in the process of shutting
781 // down blink, put a ScopePageLoadDeferrer on the stack.
782 WebView::willEnterModalLoop();
783 blink_platform_impl_
->web_database_observer_impl()
784 ->WaitForAllDatabasesToClose();
785 WebView::didExitModalLoop();
788 // Shutdown in reverse of the initialization order.
789 if (devtools_agent_message_filter_
.get()) {
790 RemoveFilter(devtools_agent_message_filter_
.get());
791 devtools_agent_message_filter_
= NULL
;
794 RemoveFilter(audio_input_message_filter_
.get());
795 audio_input_message_filter_
= NULL
;
797 #if defined(ENABLE_WEBRTC)
798 RTCPeerConnectionHandler::DestructAllHandlers();
799 // |peer_connection_factory_| cannot be deleted until after the main message
800 // loop has been destroyed. This is because there may be pending tasks that
801 // hold on to objects produced by the PC factory that depend on threads owned
802 // by the PC factory. Once those tasks have been freed, the factory can be
805 RemoveFilter(vc_manager_
->video_capture_message_filter());
808 RemoveFilter(db_message_filter_
.get());
809 db_message_filter_
= NULL
;
811 // Shutdown the file thread if it's running.
813 file_thread_
->Stop();
815 if (compositor_message_filter_
.get()) {
816 RemoveFilter(compositor_message_filter_
.get());
817 compositor_message_filter_
= NULL
;
820 media_thread_
.reset();
822 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
823 RemoveFilter(audio_message_filter_
.get());
824 audio_message_filter_
= NULL
;
826 compositor_thread_
.reset();
828 raster_worker_pool_
->Shutdown();
830 main_input_callback_
.Cancel();
831 input_handler_manager_
.reset();
832 if (input_event_filter_
.get()) {
833 RemoveFilter(input_event_filter_
.get());
834 input_event_filter_
= NULL
;
837 // RemoveEmbeddedWorkerRoute may be called while deleting
838 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
840 embedded_worker_dispatcher_
.reset();
842 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
843 // hold pointers to V8 objects (e.g., via pending requests).
844 main_thread_indexed_db_dispatcher_
.reset();
846 main_thread_compositor_task_runner_
= NULL
;
848 // Context providers must be released prior to destroying the GPU channel.
849 gpu_va_context_provider_
= nullptr;
850 shared_main_thread_contexts_
= nullptr;
852 if (gpu_channel_
.get())
853 gpu_channel_
->DestroyChannel();
857 // Clean up plugin channels before this thread goes away.
858 NPChannelBase::CleanupChannels();
861 // Shut down the message loop and the renderer scheduler before shutting down
862 // Blink. This prevents a scenario where a pending task in the message loop
863 // accesses Blink objects after Blink shuts down.
864 // This must be at the very end of the shutdown sequence. You must not touch
865 // the message loop after this.
866 renderer_scheduler_
->Shutdown();
867 main_message_loop_
.reset();
868 if (blink_platform_impl_
) {
869 blink_platform_impl_
->Shutdown();
873 lazy_tls
.Pointer()->Set(NULL
);
876 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
877 // Certain synchronous messages cannot always be processed synchronously by
878 // the browser, e.g., putting up UI and waiting for the user. This could cause
879 // a complete hang of Chrome if a windowed plugin is trying to communicate
880 // with the renderer thread since the browser's UI thread could be stuck
881 // (within a Windows API call) trying to synchronously communicate with the
882 // plugin. The remedy is to pump messages on this thread while the browser
883 // is processing this request. This creates an opportunity for re-entrancy
884 // into WebKit, so we need to take care to disable callbacks, timers, and
885 // pending network loads that could trigger such callbacks.
886 bool pumping_events
= false;
887 if (msg
->is_sync()) {
888 if (msg
->is_caller_pumping_messages()) {
889 pumping_events
= true;
893 bool notify_webkit_of_modal_loop
= true; // default value
894 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
896 #if defined(ENABLE_PLUGINS)
897 int render_view_id
= MSG_ROUTING_NONE
;
900 if (pumping_events
) {
901 renderer_scheduler_
->SuspendTimerQueue();
903 if (notify_webkit_of_modal_loop
)
904 WebView::willEnterModalLoop();
905 #if defined(ENABLE_PLUGINS)
906 RenderViewImpl
* render_view
=
907 RenderViewImpl::FromRoutingID(msg
->routing_id());
909 render_view_id
= msg
->routing_id();
910 PluginChannelHost::Broadcast(
911 new PluginMsg_SignalModalDialogEvent(render_view_id
));
916 bool rv
= ChildThreadImpl::Send(msg
);
918 if (pumping_events
) {
919 #if defined(ENABLE_PLUGINS)
920 if (render_view_id
!= MSG_ROUTING_NONE
) {
921 PluginChannelHost::Broadcast(
922 new PluginMsg_ResetModalDialogEvent(render_view_id
));
926 if (notify_webkit_of_modal_loop
)
927 WebView::didExitModalLoop();
929 renderer_scheduler_
->ResumeTimerQueue();
935 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
939 std::string
RenderThreadImpl::GetLocale() {
940 // The browser process should have passed the locale to the renderer via the
941 // --lang command line flag.
942 const base::CommandLine
& parsed_command_line
=
943 *base::CommandLine::ForCurrentProcess();
944 const std::string
& lang
=
945 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
946 DCHECK(!lang
.empty());
950 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
951 return sync_message_filter();
954 scoped_refptr
<base::SingleThreadTaskRunner
>
955 RenderThreadImpl::GetIOMessageLoopProxy() {
956 return ChildProcess::current()->io_task_runner();
959 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
960 ChildThreadImpl::GetRouter()->AddRoute(routing_id
, listener
);
961 PendingRenderFrameConnectMap::iterator it
=
962 pending_render_frame_connects_
.find(routing_id
);
963 if (it
== pending_render_frame_connects_
.end())
966 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(routing_id
);
970 scoped_refptr
<PendingRenderFrameConnect
> connection(it
->second
);
971 mojo::InterfaceRequest
<mojo::ServiceProvider
> services(
972 connection
->services().Pass());
973 mojo::ServiceProviderPtr
exposed_services(
974 connection
->exposed_services().Pass());
975 exposed_services
.set_connection_error_handler(mojo::Closure());
976 pending_render_frame_connects_
.erase(it
);
978 frame
->BindServiceRegistry(services
.Pass(), exposed_services
.Pass());
981 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
982 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id
);
985 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id
,
986 IPC::Listener
* listener
) {
987 AddRoute(routing_id
, listener
);
988 if (devtools_agent_message_filter_
.get()) {
989 devtools_agent_message_filter_
->AddEmbeddedWorkerRouteOnMainThread(
994 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id
) {
995 RemoveRoute(routing_id
);
996 if (devtools_agent_message_filter_
.get()) {
997 devtools_agent_message_filter_
->RemoveEmbeddedWorkerRouteOnMainThread(
1002 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
1004 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1005 mojo::ServiceProviderPtr exposed_services
) {
1006 std::pair
<PendingRenderFrameConnectMap::iterator
, bool> result
=
1007 pending_render_frame_connects_
.insert(std::make_pair(
1009 make_scoped_refptr(new PendingRenderFrameConnect(
1010 routing_id
, services
.Pass(), exposed_services
.Pass()))));
1011 CHECK(result
.second
) << "Inserting a duplicate item.";
1014 int RenderThreadImpl::GenerateRoutingID() {
1015 int routing_id
= MSG_ROUTING_NONE
;
1016 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
1020 void RenderThreadImpl::AddFilter(IPC::MessageFilter
* filter
) {
1021 channel()->AddFilter(filter
);
1024 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter
* filter
) {
1025 channel()->RemoveFilter(filter
);
1028 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
1029 observers_
.AddObserver(observer
);
1032 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
1033 observers_
.RemoveObserver(observer
);
1036 void RenderThreadImpl::SetResourceDispatcherDelegate(
1037 ResourceDispatcherDelegate
* delegate
) {
1038 resource_dispatcher()->set_delegate(delegate
);
1041 void RenderThreadImpl::SetResourceDispatchTaskQueue(
1042 const scoped_refptr
<base::SingleThreadTaskRunner
>& resource_task_queue
) {
1043 // Add a filter that forces resource messages to be dispatched via a
1044 // particular task runner.
1045 resource_scheduling_filter_
=
1046 new ResourceSchedulingFilter(resource_task_queue
, resource_dispatcher());
1047 channel()->AddFilter(resource_scheduling_filter_
.get());
1049 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1050 // same queue to ensure tasks are executed in the expected order.
1051 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue
);
1052 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue
);
1055 void RenderThreadImpl::EnsureWebKitInitialized() {
1056 if (blink_platform_impl_
)
1059 const base::CommandLine
& command_line
=
1060 *base::CommandLine::ForCurrentProcess();
1062 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1063 if (command_line
.HasSwitch(switches::kEnableVtune
))
1064 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1067 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
1069 blink_platform_impl_
.reset(
1070 new RendererBlinkPlatformImpl(renderer_scheduler_
.get()));
1071 blink::initialize(blink_platform_impl_
.get());
1073 v8::Isolate
* isolate
= blink::mainThreadIsolate();
1074 isolate
->SetCreateHistogramFunction(CreateHistogram
);
1075 isolate
->SetAddHistogramSampleFunction(AddHistogramSample
);
1077 main_thread_compositor_task_runner_
=
1078 renderer_scheduler_
->CompositorTaskRunner();
1080 main_input_callback_
.Reset(
1081 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived
),
1082 base::Unretained(this)));
1084 SetResourceDispatchTaskQueue(renderer_scheduler_
->LoadingTaskRunner());
1086 bool enable
= !command_line
.HasSwitch(switches::kDisableThreadedCompositing
);
1088 #if defined(OS_ANDROID)
1089 if (SynchronousCompositorFactory
* factory
=
1090 SynchronousCompositorFactory::GetInstance())
1091 compositor_task_runner_
= factory
->GetCompositorTaskRunner();
1093 if (!compositor_task_runner_
.get()) {
1094 compositor_thread_
.reset(new base::Thread("Compositor"));
1095 base::Thread::Options compositor_thread_options
;
1096 #if defined(OS_ANDROID)
1097 compositor_thread_options
.priority
= base::ThreadPriority::DISPLAY
;
1099 compositor_thread_
->StartWithOptions(compositor_thread_options
);
1100 compositor_task_runner_
= compositor_thread_
->task_runner();
1101 compositor_task_runner_
->PostTask(
1103 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
1107 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
1108 #if defined(OS_ANDROID)
1109 if (SynchronousCompositorFactory
* factory
=
1110 SynchronousCompositorFactory::GetInstance()) {
1111 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
1114 if (!input_handler_manager_client
) {
1115 scoped_refptr
<InputEventFilter
> compositor_input_event_filter(
1116 new InputEventFilter(main_input_callback_
.callback(),
1117 main_thread_compositor_task_runner_
,
1118 compositor_task_runner_
));
1119 input_handler_manager_client
= compositor_input_event_filter
.get();
1120 input_event_filter_
= compositor_input_event_filter
;
1122 input_handler_manager_
.reset(new InputHandlerManager(
1123 compositor_task_runner_
, input_handler_manager_client
,
1124 renderer_scheduler_
.get()));
1127 if (!input_event_filter_
.get()) {
1128 // Always provide an input event filter implementation to ensure consistent
1129 // input event scheduling and prioritization.
1130 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1131 // MainThreadInputEventFilter, crbug.com/436057.
1132 input_event_filter_
= new MainThreadInputEventFilter(
1133 main_input_callback_
.callback(), main_thread_compositor_task_runner_
);
1135 AddFilter(input_event_filter_
.get());
1137 scoped_refptr
<base::SingleThreadTaskRunner
> compositor_impl_side_task_runner
;
1139 compositor_impl_side_task_runner
= compositor_task_runner_
;
1141 compositor_impl_side_task_runner
= base::ThreadTaskRunnerHandle::Get();
1143 compositor_message_filter_
= new CompositorForwardingMessageFilter(
1144 compositor_impl_side_task_runner
.get());
1145 AddFilter(compositor_message_filter_
.get());
1147 RenderThreadImpl::RegisterSchemes();
1149 EnableBlinkPlatformLogChannels(
1150 command_line
.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels
));
1152 RenderMediaClient::Initialize();
1154 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
1156 devtools_agent_message_filter_
= new DevToolsAgentFilter();
1157 AddFilter(devtools_agent_message_filter_
.get());
1159 v8_sampling_profiler_
.reset(new V8SamplingProfiler());
1161 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1162 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1164 renderer_scheduler_
->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1167 ->AllowTimerSuspensionWhenProcessBackgrounded());
1169 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction
);
1171 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1172 kImageCacheSingleAllocationByteLimit
);
1174 // Hook up blink's codecs so skia can call them
1175 SkGraphics::SetImageGeneratorFromEncodedFactory(
1176 blink::WebImageGenerator::create
);
1178 if (command_line
.HasSwitch(switches::kMemoryMetrics
)) {
1179 memory_observer_
.reset(new MemoryObserver());
1180 message_loop()->AddTaskObserver(memory_observer_
.get());
1183 if (command_line
.HasSwitch(switches::kExplicitlyAllowedPorts
)) {
1184 std::string allowed_ports
=
1185 command_line
.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts
);
1186 net::SetExplicitlyAllowedPorts(allowed_ports
);
1190 void RenderThreadImpl::RegisterSchemes() {
1192 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
1193 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
1194 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
1197 WebString
chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme
));
1198 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme
);
1199 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1201 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme
);
1202 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme
);
1205 WebString
devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme
));
1206 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme
);
1209 void RenderThreadImpl::NotifyTimezoneChange() {
1210 NotifyTimezoneChangeOnThisThread();
1211 RenderThread::Get()->PostTaskToAllWebWorkers(
1212 base::Bind(&NotifyTimezoneChangeOnThisThread
));
1215 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
1216 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
1219 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
1220 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
1223 scoped_ptr
<base::SharedMemory
>
1224 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
1225 return ChildThreadImpl::AllocateSharedMemory(size
, thread_safe_sender());
1228 cc::SharedBitmapManager
* RenderThreadImpl::GetSharedBitmapManager() {
1229 return shared_bitmap_manager();
1232 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
1233 EnsureWebKitInitialized();
1234 WebScriptController::registerExtension(extension
);
1237 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
1238 idle_notification_delay_in_ms_
= initial_delay_ms
;
1240 idle_timer_
.Start(FROM_HERE
,
1241 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
1242 this, &RenderThreadImpl::IdleHandler
);
1245 void RenderThreadImpl::IdleHandler() {
1246 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
1247 GetContentClient()->renderer()->
1248 RunIdleHandlerWhenWidgetsHidden();
1249 if (run_in_foreground_tab
) {
1250 if (idle_notifications_to_skip_
> 0) {
1251 --idle_notifications_to_skip_
;
1253 ReleaseFreeMemory();
1255 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1259 ReleaseFreeMemory();
1261 // Continue the idle timer if the webkit shared timer is not suspended or
1262 // something is left to do.
1263 bool continue_timer
= !webkit_shared_timer_suspended_
;
1265 if (blink::mainThreadIsolate() &&
1266 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1267 blink_platform_impl_
->monotonicallyIncreasingTime() + 1.0)) {
1268 continue_timer
= true;
1271 // Schedule next invocation. When the tab is originally hidden, an invocation
1272 // is scheduled for kInitialIdleHandlerDelayMs in
1273 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1274 // After that, idle calls can be much less frequent, so run at a maximum of
1275 // once every kLongIdleHandlerDelayMs.
1276 // Dampen the delay using the algorithm (if delay is in seconds):
1277 // delay = delay + 1 / (delay + 2)
1278 // Using floor(delay) has a dampening effect such as:
1279 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1280 // If the delay is in milliseconds, the above formula is equivalent to:
1281 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1282 // which is equivalent to
1283 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1284 if (continue_timer
) {
1285 ScheduleIdleHandler(
1286 std::max(kLongIdleHandlerDelayMs
,
1287 idle_notification_delay_in_ms_
+
1288 1000000 / (idle_notification_delay_in_ms_
+ 2000)));
1294 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
1297 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1298 return idle_notification_delay_in_ms_
;
1301 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1302 int64 idle_notification_delay_in_ms
) {
1303 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
1306 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
1307 child_histogram_message_filter()->SendHistograms(sequence_number
);
1310 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
1311 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure
);
1314 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
1315 bool result
= false;
1316 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
1320 void RenderThreadImpl::PostponeIdleNotification() {
1321 idle_notifications_to_skip_
= 2;
1324 scoped_refptr
<media::GpuVideoAcceleratorFactories
>
1325 RenderThreadImpl::GetGpuFactories() {
1326 DCHECK(IsMainThread());
1328 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
1330 #if defined(OS_ANDROID)
1331 if (SynchronousCompositorFactory::GetInstance()) {
1332 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
1333 DLOG(WARNING
) << "Accelerated video decoding is not explicitly disabled, "
1334 "but is not supported by in-process rendering";
1340 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
1341 scoped_refptr
<media::GpuVideoAcceleratorFactories
> gpu_factories
;
1342 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner
=
1343 GetMediaThreadTaskRunner();
1344 if (gpu_va_context_provider_
.get() && !gpu_channel_host
.get()) {
1345 // The GPU channel was lost. It's possible that |gpu_va_context_provider_|
1346 // has not been made aware of that, so always create a new one.
1347 gpu_va_context_provider_
= nullptr;
1349 if (!gpu_va_context_provider_
.get() ||
1350 gpu_va_context_provider_
->DestroyedOnMainThread()) {
1351 if (!gpu_channel_host
.get()) {
1352 gpu_channel_host
= EstablishGpuChannelSync(
1353 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
1355 blink::WebGraphicsContext3D::Attributes attributes
;
1356 bool lose_context_when_out_of_memory
= false;
1357 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
1359 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1360 gpu_channel_host
.get(), attributes
,
1361 lose_context_when_out_of_memory
,
1362 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1363 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1365 GPU_VIDEO_ACCELERATOR_CONTEXT
);
1367 if (gpu_va_context_provider_
.get()) {
1368 const bool enable_video_accelerator
=
1369 !cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
);
1370 const bool enable_gpu_memory_buffer_video_frames
=
1371 #if defined(OS_MACOSX)
1372 !cmd_line
->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames
);
1374 cmd_line
->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames
);
1376 std::string image_texture_target_string
=
1377 cmd_line
->GetSwitchValueASCII(switches::kVideoImageTextureTarget
);
1378 unsigned image_texture_target
= 0;
1379 const bool parsed_image_texture_target
=
1380 base::StringToUint(image_texture_target_string
, &image_texture_target
);
1381 DCHECK(parsed_image_texture_target
);
1382 gpu_factories
= RendererGpuVideoAcceleratorFactories::Create(
1383 gpu_channel_host
.get(), media_task_runner
, gpu_va_context_provider_
,
1384 enable_gpu_memory_buffer_video_frames
, image_texture_target
,
1385 enable_video_accelerator
);
1387 return gpu_factories
;
1390 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
1391 RenderThreadImpl::CreateOffscreenContext3d() {
1392 blink::WebGraphicsContext3D::Attributes
attributes(GetOffscreenAttribs());
1393 bool lose_context_when_out_of_memory
= true;
1395 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
1396 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
1397 return make_scoped_ptr(
1398 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1399 gpu_channel_host
.get(),
1401 lose_context_when_out_of_memory
,
1402 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1403 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1407 scoped_refptr
<cc_blink::ContextProviderWebContext
>
1408 RenderThreadImpl::SharedMainThreadContextProvider() {
1409 DCHECK(IsMainThread());
1410 if (!shared_main_thread_contexts_
.get() ||
1411 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
1412 shared_main_thread_contexts_
= NULL
;
1413 #if defined(OS_ANDROID)
1414 SynchronousCompositorFactory
* factory
=
1415 SynchronousCompositorFactory::GetInstance();
1416 if (factory
&& factory
->OverrideWithFactory()) {
1417 shared_main_thread_contexts_
= factory
->CreateOffscreenContextProvider(
1418 GetOffscreenAttribs(), "Offscreen-MainThread");
1421 if (!shared_main_thread_contexts_
.get()) {
1422 shared_main_thread_contexts_
= ContextProviderCommandBuffer::Create(
1423 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT
);
1425 if (shared_main_thread_contexts_
.get() &&
1426 !shared_main_thread_contexts_
->BindToCurrentThread())
1427 shared_main_thread_contexts_
= NULL
;
1429 return shared_main_thread_contexts_
;
1432 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
1433 if (!audio_renderer_mixer_manager_
) {
1434 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
1435 GetAudioHardwareConfig()));
1438 return audio_renderer_mixer_manager_
.get();
1441 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1442 if (!audio_hardware_config_
) {
1443 media::AudioParameters input_params
;
1444 media::AudioParameters output_params
;
1445 Send(new ViewHostMsg_GetAudioHardwareConfig(
1446 &input_params
, &output_params
));
1448 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1449 input_params
, output_params
));
1452 return audio_hardware_config_
.get();
1455 base::WaitableEvent
* RenderThreadImpl::GetShutdownEvent() {
1456 return ChildProcess::current()->GetShutDownEvent();
1460 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1461 const base::string16
& str
) {
1462 Send(new RenderProcessHostMsg_PreCacheFontCharacters(log_font
, str
));
1467 ServiceRegistry
* RenderThreadImpl::GetServiceRegistry() {
1468 return service_registry();
1471 bool RenderThreadImpl::IsGpuRasterizationForced() {
1472 return is_gpu_rasterization_forced_
;
1475 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1476 return is_gpu_rasterization_enabled_
;
1479 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1480 return gpu_rasterization_msaa_sample_count_
;
1483 bool RenderThreadImpl::IsLcdTextEnabled() {
1484 return is_lcd_text_enabled_
;
1487 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1488 return is_distance_field_text_enabled_
;
1491 bool RenderThreadImpl::IsZeroCopyEnabled() {
1492 return is_zero_copy_enabled_
;
1495 bool RenderThreadImpl::IsPersistentGpuMemoryBufferEnabled() {
1496 return is_persistent_gpu_memory_buffer_enabled_
;
1499 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1500 return is_elastic_overscroll_enabled_
;
1503 std::vector
<unsigned> RenderThreadImpl::GetImageTextureTargets() {
1504 return use_image_texture_targets_
;
1507 scoped_refptr
<base::SingleThreadTaskRunner
>
1508 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1509 return main_thread_compositor_task_runner_
;
1512 scoped_refptr
<base::SingleThreadTaskRunner
>
1513 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1514 return compositor_task_runner_
;
1517 gpu::GpuMemoryBufferManager
* RenderThreadImpl::GetGpuMemoryBufferManager() {
1518 return gpu_memory_buffer_manager();
1521 scheduler::RendererScheduler
* RenderThreadImpl::GetRendererScheduler() {
1522 return renderer_scheduler_
.get();
1525 cc::ContextProvider
* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1526 return SharedMainThreadContextProvider().get();
1529 scoped_ptr
<cc::BeginFrameSource
>
1530 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id
) {
1531 #if defined(OS_ANDROID)
1532 if (SynchronousCompositorFactory
* factory
=
1533 SynchronousCompositorFactory::GetInstance()) {
1534 return factory
->CreateExternalBeginFrameSource(routing_id
);
1537 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1538 compositor_message_filter_
.get(), sync_message_filter(), routing_id
));
1541 cc::TaskGraphRunner
* RenderThreadImpl::GetTaskGraphRunner() {
1542 return raster_worker_pool_
->GetTaskGraphRunner();
1545 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1546 return is_gather_pixel_refs_enabled_
;
1549 bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1550 return is_threaded_animation_enabled_
;
1553 bool RenderThreadImpl::IsMainThread() {
1557 scoped_refptr
<base::SingleThreadTaskRunner
>
1558 RenderThreadImpl::GetIOThreadTaskRunner() {
1559 return io_thread_task_runner_
;
1562 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1564 return scoped_ptr
<base::SharedMemory
>(
1565 HostAllocateSharedMemoryBuffer(size
));
1568 CreateCommandBufferResult
RenderThreadImpl::CreateViewCommandBuffer(
1570 const GPUCreateCommandBufferConfig
& init_params
,
1573 "RenderThreadImpl::CreateViewCommandBuffer",
1577 CreateCommandBufferResult result
= CREATE_COMMAND_BUFFER_FAILED
;
1578 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1584 // Allow calling this from the compositor thread.
1585 thread_safe_sender()->Send(message
);
1590 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1591 notify_webkit_of_modal_loop_
= false;
1594 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1595 base::ObserverListBase
<RenderProcessObserver
>::Iterator
it(&observers_
);
1596 RenderProcessObserver
* observer
;
1597 while ((observer
= it
.GetNext()) != NULL
) {
1598 if (observer
->OnControlMessageReceived(msg
))
1602 // Some messages are handled by delegates.
1603 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1604 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1605 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1609 bool handled
= true;
1610 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1611 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame
, OnCreateNewFrame
)
1612 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy
, OnCreateNewFrameProxy
)
1613 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1614 OnSetZoomLevelForCurrentURL
)
1615 // TODO(port): removed from render_messages_internal.h;
1616 // is there a new non-windows message I should add here?
1617 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1618 IPC_MESSAGE_HANDLER(ViewMsg_NetworkConnectionChanged
,
1619 OnNetworkConnectionChanged
)
1620 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker
, OnCreateNewSharedWorker
)
1621 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1622 #if defined(OS_ANDROID)
1623 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1624 OnSetWebKitSharedTimersSuspended
)
1626 #if defined(OS_MACOSX)
1627 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1629 #if defined(ENABLE_PLUGINS)
1630 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1632 IPC_MESSAGE_UNHANDLED(handled
= false)
1633 IPC_END_MESSAGE_MAP()
1637 void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded
) {
1638 ChildThreadImpl::OnProcessBackgrounded(backgrounded
);
1641 renderer_scheduler_
->OnRendererBackgrounded();
1643 renderer_scheduler_
->OnRendererForegrounded();
1646 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params
) {
1647 CompositorDependencies
* compositor_deps
= this;
1648 RenderFrameImpl::CreateFrame(
1649 params
.routing_id
, params
.proxy_routing_id
, params
.opener_routing_id
,
1650 params
.parent_routing_id
, params
.previous_sibling_routing_id
,
1651 params
.replication_state
, compositor_deps
, params
.widget_params
);
1654 void RenderThreadImpl::OnCreateNewFrameProxy(
1656 int render_view_routing_id
,
1657 int opener_routing_id
,
1658 int parent_routing_id
,
1659 const FrameReplicationState
& replicated_state
) {
1660 RenderFrameProxy::CreateFrameProxy(routing_id
, render_view_routing_id
,
1661 opener_routing_id
, parent_routing_id
,
1665 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1666 const std::string
& host
,
1667 double zoom_level
) {
1668 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1669 RenderView::ForEach(&zoomer
);
1672 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1673 EnsureWebKitInitialized();
1674 CompositorDependencies
* compositor_deps
= this;
1675 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1676 RenderViewImpl::Create(compositor_deps
, params
, false);
1679 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1680 CauseForGpuLaunch cause_for_gpu_launch
) {
1681 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1683 if (gpu_channel_
.get()) {
1684 // Do nothing if we already have a GPU channel or are already
1685 // establishing one.
1686 if (!gpu_channel_
->IsLost())
1687 return gpu_channel_
.get();
1689 // Recreate the channel if it has been lost.
1690 gpu_channel_
->DestroyChannel();
1691 gpu_channel_
= NULL
;
1694 // Ask the browser for the channel name.
1696 IPC::ChannelHandle channel_handle
;
1697 gpu::GPUInfo gpu_info
;
1698 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1702 #if defined(OS_POSIX)
1703 channel_handle
.socket
.fd
== -1 ||
1705 channel_handle
.name
.empty()) {
1706 // Otherwise cancel the connection.
1710 GetContentClient()->SetGpuInfo(gpu_info
);
1712 // Cache some variables that are needed on the compositor thread for our
1713 // implementation of GpuChannelHostFactory.
1714 io_thread_task_runner_
= ChildProcess::current()->io_task_runner();
1717 GpuChannelHost::Create(this,
1721 ChildProcess::current()->GetShutDownEvent(),
1722 gpu_memory_buffer_manager());
1723 return gpu_channel_
.get();
1726 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1727 blink::WebMediaStreamCenterClient
* client
) {
1728 #if defined(ENABLE_WEBRTC)
1729 if (!media_stream_center_
) {
1730 media_stream_center_
= GetContentClient()->renderer()
1731 ->OverrideCreateWebMediaStreamCenter(client
);
1732 if (!media_stream_center_
) {
1733 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1734 new MediaStreamCenter(client
, GetPeerConnectionDependencyFactory()));
1735 media_stream_center_
= media_stream_center
.release();
1739 return media_stream_center_
;
1742 #if defined(ENABLE_WEBRTC)
1743 PeerConnectionDependencyFactory
*
1744 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1745 return peer_connection_factory_
.get();
1749 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1750 if (!gpu_channel_
.get())
1753 if (gpu_channel_
->IsLost())
1756 return gpu_channel_
.get();
1759 #if defined(ENABLE_PLUGINS)
1760 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1761 EnsureWebKitInitialized();
1762 // The call below will cause a GetPlugins call with refresh=true, but at this
1763 // point we already know that the browser has refreshed its list, so disable
1764 // refresh temporarily to prevent each renderer process causing the list to be
1766 blink_platform_impl_
->set_plugin_refresh_allowed(false);
1767 blink::resetPluginCache(reload_pages
);
1768 blink_platform_impl_
->set_plugin_refresh_allowed(true);
1770 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1774 void RenderThreadImpl::OnNetworkConnectionChanged(
1775 net::NetworkChangeNotifier::ConnectionType type
,
1776 double max_bandwidth_mbps
) {
1777 EnsureWebKitInitialized();
1778 bool online
= type
!= net::NetworkChangeNotifier::CONNECTION_NONE
;
1779 WebNetworkStateNotifier::setOnLine(online
);
1781 RenderProcessObserver
, observers_
, NetworkStateChanged(online
));
1782 WebNetworkStateNotifier::setWebConnection(
1783 NetConnectionTypeToWebConnectionType(type
), max_bandwidth_mbps
);
1786 void RenderThreadImpl::OnUpdateTimezone(const std::string
& zone_id
) {
1787 if (!blink_platform_impl_
)
1789 if (!zone_id
.empty()) {
1790 icu::TimeZone
*new_zone
= icu::TimeZone::createTimeZone(
1791 icu::UnicodeString::fromUTF8(zone_id
));
1792 icu::TimeZone::adoptDefault(new_zone
);
1793 VLOG(1) << "ICU default timezone is set to " << zone_id
;
1795 NotifyTimezoneChange();
1798 #if defined(OS_ANDROID)
1799 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1800 EnsureWebKitInitialized();
1802 renderer_scheduler_
->SuspendTimerQueue();
1804 renderer_scheduler_
->ResumeTimerQueue();
1806 webkit_shared_timer_suspended_
= suspend
;
1810 #if defined(OS_MACOSX)
1811 void RenderThreadImpl::OnUpdateScrollbarTheme(
1812 const ViewMsg_UpdateScrollbarTheme_Params
& params
) {
1813 EnsureWebKitInitialized();
1814 static_cast<WebScrollbarBehaviorImpl
*>(
1815 blink_platform_impl_
->scrollbarBehavior())
1816 ->set_jump_on_track_click(params
.jump_on_track_click
);
1818 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
1819 params
.initial_button_delay
, params
.autoscroll_button_delay
,
1820 params
.preferred_scroller_style
, params
.redraw
,
1821 params
.scroll_animation_enabled
, params
.button_placement
);
1825 void RenderThreadImpl::OnCreateNewSharedWorker(
1826 const WorkerProcessMsg_CreateWorker_Params
& params
) {
1827 // EmbeddedSharedWorkerStub will self-destruct.
1828 new EmbeddedSharedWorkerStub(params
.url
,
1830 params
.content_security_policy
,
1831 params
.security_policy_type
,
1832 params
.pause_on_start
,
1836 void RenderThreadImpl::OnMemoryPressure(
1837 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1838 ReleaseFreeMemory();
1840 // Do not call into blink if it is not initialized.
1841 if (blink_platform_impl_
) {
1842 blink::WebCache::pruneAll();
1844 if (blink::mainThreadIsolate()) {
1845 // Trigger full v8 garbage collection on memory pressure notifications.
1846 // This will potentially hang the renderer for a long time, however, when
1847 // we receive a memory pressure notification, we might be about to be
1849 blink::mainThreadIsolate()->LowMemoryNotification();
1850 RenderThread::Get()->PostTaskToAllWebWorkers(
1851 base::Bind(&LowMemoryNotificationOnThisThread
));
1854 if (memory_pressure_level
==
1855 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
1856 // Clear the image cache.
1857 blink::WebImageCache::clear();
1859 // Purge Skia font cache, by setting it to 0 and then again to the
1861 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1862 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1867 scoped_refptr
<base::SingleThreadTaskRunner
>
1868 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1869 DCHECK(message_loop() == base::MessageLoop::current());
1870 if (!file_thread_
) {
1871 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1872 file_thread_
->Start();
1874 return file_thread_
->task_runner();
1877 scoped_refptr
<base::SingleThreadTaskRunner
>
1878 RenderThreadImpl::GetMediaThreadTaskRunner() {
1879 DCHECK(message_loop() == base::MessageLoop::current());
1880 if (!media_thread_
) {
1881 media_thread_
.reset(new base::Thread("Media"));
1882 media_thread_
->Start();
1884 #if defined(OS_ANDROID)
1885 renderer_demuxer_
= new RendererDemuxerAndroid();
1886 AddFilter(renderer_demuxer_
.get());
1889 return media_thread_
->task_runner();
1892 base::TaskRunner
* RenderThreadImpl::GetWorkerTaskRunner() {
1893 return raster_worker_pool_
.get();
1896 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1897 blink_platform_impl_
->sampleGamepads(*data
);
1900 bool RenderThreadImpl::RendererIsHidden() const {
1901 return widget_count_
> 0 && hidden_widget_count_
== widget_count_
;
1904 void RenderThreadImpl::WidgetCreated() {
1905 bool renderer_was_hidden
= RendererIsHidden();
1907 if (renderer_was_hidden
)
1908 OnRendererVisible();
1911 void RenderThreadImpl::WidgetDestroyed() {
1912 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1913 // unhidden before WidgetDestroyed is called.
1914 DCHECK_GT(widget_count_
, 0);
1915 DCHECK_GT(widget_count_
, hidden_widget_count_
);
1917 if (RendererIsHidden())
1921 void RenderThreadImpl::WidgetHidden() {
1922 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1923 hidden_widget_count_
++;
1924 if (RendererIsHidden())
1928 void RenderThreadImpl::WidgetRestored() {
1929 bool renderer_was_hidden
= RendererIsHidden();
1930 DCHECK_GT(hidden_widget_count_
, 0);
1931 hidden_widget_count_
--;
1932 if (renderer_was_hidden
)
1933 OnRendererVisible();
1936 void RenderThreadImpl::OnRendererHidden() {
1937 renderer_scheduler_
->OnRendererHidden();
1939 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1940 // scheduled by the RendererScheduler - http://crbug.com/469210.
1941 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1942 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1945 void RenderThreadImpl::OnRendererVisible() {
1946 renderer_scheduler_
->OnRendererVisible();
1948 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1951 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1954 void RenderThreadImpl::ReleaseFreeMemory() {
1955 base::allocator::ReleaseFreeMemory();
1956 discardable_shared_memory_manager()->ReleaseFreeMemory();
1958 if (blink_platform_impl_
)
1959 blink::decommitFreeableMemory();
1962 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1964 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1965 mojo::ServiceProviderPtr exposed_services
)
1966 : routing_id_(routing_id
),
1967 services_(services
.Pass()),
1968 exposed_services_(exposed_services
.Pass()) {
1969 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1970 // is received. In that case, the RenderFrameHost should close the connection,
1971 // which is detected by setting an error handler on |exposed_services_|.
1972 exposed_services_
.set_connection_error_handler(base::Bind(
1973 &RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError
,
1974 base::Unretained(this)));
1977 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1980 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1982 RenderThreadImpl::current()->pending_render_frame_connects_
.erase(
1984 DCHECK_EQ(1u, erased
);
1987 } // namespace content