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/debug/trace_event.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/memory/discardable_memory.h"
18 #include "base/memory/discardable_memory_emulated.h"
19 #include "base/memory/discardable_memory_shmem_allocator.h"
20 #include "base/memory/shared_memory.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/metrics/stats_table.h"
24 #include "base/path_service.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/strings/string16.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_tokenizer.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/threading/thread_local.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/values.h"
33 #include "cc/base/switches.h"
34 #include "cc/blink/web_external_bitmap_impl.h"
35 #include "cc/blink/web_layer_impl.h"
36 #include "cc/resources/raster_worker_pool.h"
37 #include "content/child/appcache/appcache_dispatcher.h"
38 #include "content/child/appcache/appcache_frontend_impl.h"
39 #include "content/child/child_discardable_shared_memory_manager.h"
40 #include "content/child/child_gpu_memory_buffer_manager.h"
41 #include "content/child/child_histogram_message_filter.h"
42 #include "content/child/content_child_helpers.h"
43 #include "content/child/db_message_filter.h"
44 #include "content/child/indexed_db/indexed_db_dispatcher.h"
45 #include "content/child/indexed_db/indexed_db_message_filter.h"
46 #include "content/child/npapi/npobject_util.h"
47 #include "content/child/plugin_messages.h"
48 #include "content/child/resource_dispatcher.h"
49 #include "content/child/runtime_features.h"
50 #include "content/child/thread_safe_sender.h"
51 #include "content/child/web_database_observer_impl.h"
52 #include "content/child/worker_task_runner.h"
53 #include "content/common/child_process_messages.h"
54 #include "content/common/content_constants_internal.h"
55 #include "content/common/database_messages.h"
56 #include "content/common/dom_storage/dom_storage_messages.h"
57 #include "content/common/frame_messages.h"
58 #include "content/common/gpu/client/context_provider_command_buffer.h"
59 #include "content/common/gpu/client/gpu_channel_host.h"
60 #include "content/common/gpu/gpu_messages.h"
61 #include "content/common/gpu/gpu_process_launch_causes.h"
62 #include "content/common/render_frame_setup.mojom.h"
63 #include "content/common/resource_messages.h"
64 #include "content/common/view_messages.h"
65 #include "content/common/worker_messages.h"
66 #include "content/public/common/content_constants.h"
67 #include "content/public/common/content_paths.h"
68 #include "content/public/common/content_switches.h"
69 #include "content/public/common/renderer_preferences.h"
70 #include "content/public/common/url_constants.h"
71 #include "content/public/renderer/content_renderer_client.h"
72 #include "content/public/renderer/render_process_observer.h"
73 #include "content/public/renderer/render_view_visitor.h"
74 #include "content/renderer/devtools/devtools_agent_filter.h"
75 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
76 #include "content/renderer/dom_storage/webstoragearea_impl.h"
77 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
78 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
79 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
80 #include "content/renderer/gpu/compositor_output_surface.h"
81 #include "content/renderer/input/input_event_filter.h"
82 #include "content/renderer/input/input_handler_manager.h"
83 #include "content/renderer/media/aec_dump_message_filter.h"
84 #include "content/renderer/media/audio_input_message_filter.h"
85 #include "content/renderer/media/audio_message_filter.h"
86 #include "content/renderer/media/audio_renderer_mixer_manager.h"
87 #include "content/renderer/media/media_stream_center.h"
88 #include "content/renderer/media/midi_message_filter.h"
89 #include "content/renderer/media/render_media_client.h"
90 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
91 #include "content/renderer/media/video_capture_impl_manager.h"
92 #include "content/renderer/media/video_capture_message_filter.h"
93 #include "content/renderer/net_info_helper.h"
94 #include "content/renderer/p2p/socket_dispatcher.h"
95 #include "content/renderer/render_frame_proxy.h"
96 #include "content/renderer/render_process_impl.h"
97 #include "content/renderer/render_view_impl.h"
98 #include "content/renderer/renderer_blink_platform_impl.h"
99 #include "content/renderer/scheduler/renderer_scheduler.h"
100 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
101 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
102 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
103 #include "gin/public/debug.h"
104 #include "ipc/ipc_channel_handle.h"
105 #include "ipc/ipc_platform_file.h"
106 #include "ipc/mojo/ipc_channel_mojo.h"
107 #include "media/base/audio_hardware_config.h"
108 #include "media/base/media.h"
109 #include "media/filters/gpu_video_accelerator_factories.h"
110 #include "mojo/common/common_type_converters.h"
111 #include "net/base/net_errors.h"
112 #include "net/base/net_util.h"
113 #include "skia/ext/event_tracer_impl.h"
114 #include "third_party/WebKit/public/platform/WebString.h"
115 #include "third_party/WebKit/public/platform/WebThread.h"
116 #include "third_party/WebKit/public/web/WebColorName.h"
117 #include "third_party/WebKit/public/web/WebDatabase.h"
118 #include "third_party/WebKit/public/web/WebDocument.h"
119 #include "third_party/WebKit/public/web/WebFrame.h"
120 #include "third_party/WebKit/public/web/WebImageCache.h"
121 #include "third_party/WebKit/public/web/WebKit.h"
122 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
123 #include "third_party/WebKit/public/web/WebPopupMenu.h"
124 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
125 #include "third_party/WebKit/public/web/WebScriptController.h"
126 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
127 #include "third_party/WebKit/public/web/WebView.h"
128 #include "third_party/skia/include/core/SkGraphics.h"
129 #include "ui/base/layout.h"
130 #include "ui/base/ui_base_switches.h"
131 #include "v8/include/v8.h"
133 #if defined(OS_ANDROID)
134 #include <cpu-features.h>
135 #include "content/renderer/android/synchronous_compositor_factory.h"
136 #include "content/renderer/media/android/renderer_demuxer_android.h"
139 #if defined(OS_MACOSX)
140 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
143 #if defined(OS_POSIX)
144 #include "ipc/ipc_channel_posix.h"
152 #include "content/child/npapi/np_channel_base.h"
155 #if defined(ENABLE_PLUGINS)
156 #include "content/renderer/npapi/plugin_channel_host.h"
159 #if defined(ENABLE_WEBRTC)
160 #include "content/renderer/media/peer_connection_tracker.h"
161 #include "content/renderer/media/rtc_peer_connection_handler.h"
162 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
163 #include "content/renderer/media/webrtc_identity_service.h"
166 #ifdef ENABLE_VTUNE_JIT_INTERFACE
167 #include "v8/src/third_party/vtune/v8-vtune.h"
170 using base::ThreadRestrictions
;
171 using blink::WebDocument
;
172 using blink::WebFrame
;
173 using blink::WebNetworkStateNotifier
;
174 using blink::WebRuntimeFeatures
;
175 using blink::WebScriptController
;
176 using blink::WebSecurityPolicy
;
177 using blink::WebString
;
178 using blink::WebView
;
184 const int64 kInitialIdleHandlerDelayMs
= 1000;
185 const int64 kLongIdleHandlerDelayMs
= 30*1000;
187 // Maximum allocation size allowed for image scaling filters that
188 // require pre-scaling. Skia will fallback to a filter that doesn't
189 // require pre-scaling if the default filter would require an
190 // allocation that exceeds this limit.
191 const size_t kImageCacheSingleAllocationByteLimit
= 64 * 1024 * 1024;
193 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
=
196 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
197 // incorrectly from the wrong thread.
198 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
199 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
201 class RenderViewZoomer
: public RenderViewVisitor
{
203 RenderViewZoomer(const std::string
& scheme
,
204 const std::string
& host
,
205 double zoom_level
) : scheme_(scheme
),
207 zoom_level_(zoom_level
) {
210 bool Visit(RenderView
* render_view
) override
{
211 WebView
* webview
= render_view
->GetWebView();
212 WebDocument document
= webview
->mainFrame()->document();
214 // Don't set zoom level for full-page plugin since they don't use the same
216 if (document
.isPluginDocument())
218 GURL
url(document
.url());
219 // Empty scheme works as wildcard that matches any scheme,
220 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
221 (scheme_
.empty() || scheme_
== url
.scheme()) &&
222 !static_cast<RenderViewImpl
*>(render_view
)
223 ->uses_temporary_zoom_level()) {
224 webview
->hidePopups();
225 webview
->setZoomLevel(zoom_level_
);
231 const std::string scheme_
;
232 const std::string host_
;
233 const double zoom_level_
;
235 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
238 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
239 if (host
== "mail.google.com")
241 if (host
== "docs.google.com" || host
== "drive.google.com")
243 if (host
== "plus.google.com")
245 return std::string();
248 void* CreateHistogram(
249 const char *name
, int min
, int max
, size_t buckets
) {
252 std::string histogram_name
;
253 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
254 if (render_thread_impl
) { // Can be null in tests.
255 histogram_name
= render_thread_impl
->
256 histogram_customizer()->ConvertToCustomHistogramName(name
);
258 histogram_name
= std::string(name
);
260 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
261 histogram_name
, min
, max
, buckets
,
262 base::Histogram::kUmaTargetedHistogramFlag
);
266 void AddHistogramSample(void* hist
, int sample
) {
267 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
268 histogram
->Add(sample
);
271 scoped_ptr
<base::SharedMemory
> AllocateSharedMemoryFunction(size_t size
) {
272 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size
);
275 void EnableBlinkPlatformLogChannels(const std::string
& channels
) {
276 if (channels
.empty())
278 base::StringTokenizer
t(channels
, ", ");
280 blink::enableLogChannel(t
.token().c_str());
283 void NotifyTimezoneChangeOnThisThread() {
284 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
287 v8::Date::DateTimeConfigurationChangeNotification(isolate
);
290 class RenderFrameSetupImpl
: public mojo::InterfaceImpl
<RenderFrameSetup
> {
292 RenderFrameSetupImpl()
293 : routing_id_highmark_(-1) {
296 void GetServiceProviderForFrame(
297 int32_t frame_routing_id
,
298 mojo::InterfaceRequest
<mojo::ServiceProvider
> request
) override
{
299 // TODO(morrita): This is for investigating http://crbug.com/415059 and
300 // should be removed once it is fixed.
301 CHECK_LT(routing_id_highmark_
, frame_routing_id
);
302 routing_id_highmark_
= frame_routing_id
;
304 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(frame_routing_id
);
305 // We can receive a GetServiceProviderForFrame message for a frame not yet
306 // created due to a race between the message and a ViewMsg_New IPC that
307 // triggers creation of the RenderFrame we want.
309 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
310 frame_routing_id
, request
.PassMessagePipe());
314 frame
->BindServiceRegistry(request
.PassMessagePipe());
318 int32_t routing_id_highmark_
;
321 void CreateRenderFrameSetup(mojo::InterfaceRequest
<RenderFrameSetup
> request
) {
322 mojo::BindToRequest(new RenderFrameSetupImpl(), &request
);
325 bool ShouldUseMojoChannel() {
326 return CommandLine::ForCurrentProcess()->HasSwitch(
327 switches::kEnableRendererMojoChannel
) ||
328 IPC::ChannelMojo::ShouldBeUsed();
331 blink::WebGraphicsContext3D::Attributes
GetOffscreenAttribs() {
332 blink::WebGraphicsContext3D::Attributes attributes
;
333 attributes
.shareResources
= true;
334 attributes
.depth
= false;
335 attributes
.stencil
= false;
336 attributes
.antialias
= false;
337 attributes
.noAutomaticFlushes
= true;
343 // For measuring memory usage after each task. Behind a command line flag.
344 class MemoryObserver
: public base::MessageLoop::TaskObserver
{
347 ~MemoryObserver() override
{}
349 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
351 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
352 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
356 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
359 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
360 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
361 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
362 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
365 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
367 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
368 const std::string
& host
, size_t view_count
) {
369 if (CommandLine::ForCurrentProcess()->HasSwitch(
370 switches::kDisableHistogramCustomizer
)) {
373 // Check if all RenderViews are displaying a page from the same host. If there
374 // is only one RenderView, the common host is this view's host. If there are
375 // many, check if this one shares the common host of the other
376 // RenderViews. It's ok to not detect some cases where the RenderViews share a
377 // common host. This information is only used for producing custom histograms.
380 else if (host
!= common_host_
)
381 SetCommonHost(std::string());
384 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
385 const char* histogram_name
) const {
386 std::string
name(histogram_name
);
387 if (!common_host_histogram_suffix_
.empty() &&
388 custom_histograms_
.find(name
) != custom_histograms_
.end())
389 name
+= common_host_histogram_suffix_
;
393 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
394 const std::string
& host
) {
395 if (host
!= common_host_
) {
397 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
398 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram
);
402 RenderThreadImpl
* RenderThreadImpl::current() {
403 return lazy_tls
.Pointer()->Get();
406 // When we run plugins in process, we actually run them on the render thread,
407 // which means that we need to make the render thread pump UI events.
408 RenderThreadImpl::RenderThreadImpl()
409 : ChildThread(Options(ShouldUseMojoChannel())) {
413 RenderThreadImpl::RenderThreadImpl(const std::string
& channel_name
)
414 : ChildThread(Options(channel_name
, ShouldUseMojoChannel())) {
418 RenderThreadImpl::RenderThreadImpl(
419 scoped_ptr
<base::MessageLoop
> main_message_loop
)
420 : ChildThread(Options(ShouldUseMojoChannel())),
421 main_message_loop_(main_message_loop
.Pass()) {
425 void RenderThreadImpl::Init() {
426 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
428 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
429 base::PlatformThread::CurrentId(),
430 kTraceEventRendererMainThreadSortIndex
);
432 #if defined(OS_MACOSX) || defined(OS_ANDROID)
433 // On Mac and Android, the select popups are rendered by the browser.
434 blink::WebView::setUseExternalPopupMenus(true);
437 lazy_tls
.Pointer()->Set(this);
439 // Register this object as the main thread.
440 ChildProcess::current()->set_main_thread(this);
442 // In single process the single process is all there is.
443 suspend_webkit_shared_timer_
= true;
444 notify_webkit_of_modal_loop_
= true;
445 webkit_shared_timer_suspended_
= false;
447 hidden_widget_count_
= 0;
448 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
449 idle_notifications_to_skip_
= 0;
450 layout_test_mode_
= false;
452 appcache_dispatcher_
.reset(
453 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
454 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
455 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
456 thread_safe_sender()));
457 renderer_scheduler_
= RendererScheduler::Create();
458 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
460 media_stream_center_
= NULL
;
462 db_message_filter_
= new DBMessageFilter();
463 AddFilter(db_message_filter_
.get());
465 vc_manager_
.reset(new VideoCaptureImplManager());
466 AddFilter(vc_manager_
->video_capture_message_filter());
468 #if defined(ENABLE_WEBRTC)
469 peer_connection_tracker_
.reset(new PeerConnectionTracker());
470 AddObserver(peer_connection_tracker_
.get());
472 p2p_socket_dispatcher_
=
473 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
474 AddFilter(p2p_socket_dispatcher_
.get());
476 webrtc_identity_service_
.reset(new WebRTCIdentityService());
478 aec_dump_message_filter_
=
479 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
480 message_loop()->message_loop_proxy());
481 AddFilter(aec_dump_message_filter_
.get());
483 peer_connection_factory_
.reset(new PeerConnectionDependencyFactory(
484 p2p_socket_dispatcher_
.get()));
485 #endif // defined(ENABLE_WEBRTC)
487 audio_input_message_filter_
=
488 new AudioInputMessageFilter(GetIOMessageLoopProxy());
489 AddFilter(audio_input_message_filter_
.get());
491 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
492 AddFilter(audio_message_filter_
.get());
494 midi_message_filter_
= new MidiMessageFilter(GetIOMessageLoopProxy());
495 AddFilter(midi_message_filter_
.get());
497 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
499 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
501 GetContentClient()->renderer()->RenderThreadStarted();
503 InitSkiaEventTracer();
505 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
507 is_impl_side_painting_enabled_
=
508 command_line
.HasSwitch(switches::kEnableImplSidePainting
);
509 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
510 is_impl_side_painting_enabled_
);
512 is_zero_copy_enabled_
= command_line
.HasSwitch(switches::kEnableZeroCopy
);
514 #if defined(OS_MACOSX) || defined(OS_ANDROID)
515 // TODO(danakj): If changing these also update NumberOfRendererRasterThreads
516 // in compositor_util.cc. We should be using methods from compositor_util here
517 // instead of inspecting flags.
518 is_one_copy_enabled_
= command_line
.HasSwitch(switches::kEnableOneCopy
);
520 is_one_copy_enabled_
= !command_line
.HasSwitch(switches::kDisableOneCopy
);
523 use_image_external_
= command_line
.HasSwitch(switches::kUseImageExternal
);
525 if (command_line
.HasSwitch(switches::kDisableLCDText
)) {
526 is_lcd_text_enabled_
= false;
527 } else if (command_line
.HasSwitch(switches::kEnableLCDText
)) {
528 is_lcd_text_enabled_
= true;
530 #if defined(OS_ANDROID)
531 is_lcd_text_enabled_
= false;
533 is_lcd_text_enabled_
= true;
537 is_gpu_rasterization_enabled_
=
538 command_line
.HasSwitch(switches::kEnableGpuRasterization
);
539 is_gpu_rasterization_forced_
=
540 command_line
.HasSwitch(switches::kForceGpuRasterization
);
542 if (command_line
.HasSwitch(switches::kDisableDistanceFieldText
)) {
543 is_distance_field_text_enabled_
= false;
544 } else if (command_line
.HasSwitch(switches::kEnableDistanceFieldText
)) {
545 is_distance_field_text_enabled_
= true;
547 is_distance_field_text_enabled_
= false;
550 // Note that under Linux, the media library will normally already have
551 // been initialized by the Zygote before this instance became a Renderer.
552 base::FilePath media_path
;
553 PathService::Get(DIR_MEDIA_LIBS
, &media_path
);
554 if (!media_path
.empty())
555 media::InitializeMediaLibrary(media_path
);
557 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
558 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
560 std::vector
<base::DiscardableMemoryType
> supported_types
;
561 base::DiscardableMemory::GetSupportedTypes(&supported_types
);
562 DCHECK(!supported_types
.empty());
564 // The default preferred type is always the first one in list.
565 base::DiscardableMemoryType type
= supported_types
[0];
567 if (command_line
.HasSwitch(switches::kUseDiscardableMemory
)) {
568 std::string requested_type_name
= command_line
.GetSwitchValueASCII(
569 switches::kUseDiscardableMemory
);
570 base::DiscardableMemoryType requested_type
=
571 base::DiscardableMemory::GetNamedType(requested_type_name
);
572 if (std::find(supported_types
.begin(),
573 supported_types
.end(),
574 requested_type
) != supported_types
.end()) {
575 type
= requested_type
;
577 LOG(ERROR
) << "Requested discardable memory type is not supported.";
581 base::DiscardableMemory::SetPreferredType(type
);
583 if (is_impl_side_painting_enabled_
) {
584 int num_raster_threads
= 0;
585 std::string string_value
=
586 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
587 bool parsed_num_raster_threads
=
588 base::StringToInt(string_value
, &num_raster_threads
);
589 DCHECK(parsed_num_raster_threads
) << string_value
;
590 DCHECK_GT(num_raster_threads
, 0);
591 cc::RasterWorkerPool::SetNumRasterThreads(num_raster_threads
);
594 base::DiscardableMemoryShmemAllocator::SetInstance(
595 ChildThread::discardable_shared_memory_manager());
597 service_registry()->AddService
<RenderFrameSetup
>(
598 base::Bind(CreateRenderFrameSetup
));
600 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
603 RenderThreadImpl::~RenderThreadImpl() {
604 for (std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
605 pending_render_frame_connects_
.begin();
606 it
!= pending_render_frame_connects_
.end();
608 mojo::CloseRaw(it
->second
);
612 void RenderThreadImpl::Shutdown() {
614 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
616 ChildThread::Shutdown();
618 if (memory_observer_
) {
619 message_loop()->RemoveTaskObserver(memory_observer_
.get());
620 memory_observer_
.reset();
623 // Wait for all databases to be closed.
624 if (blink_platform_impl_
) {
625 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
626 // processing timer events while we're already in the process of shutting
627 // down blink, put a ScopePageLoadDeferrer on the stack.
628 WebView::willEnterModalLoop();
629 blink_platform_impl_
->web_database_observer_impl()
630 ->WaitForAllDatabasesToClose();
631 WebView::didExitModalLoop();
634 // Shutdown in reverse of the initialization order.
635 if (devtools_agent_message_filter_
.get()) {
636 RemoveFilter(devtools_agent_message_filter_
.get());
637 devtools_agent_message_filter_
= NULL
;
640 RemoveFilter(audio_input_message_filter_
.get());
641 audio_input_message_filter_
= NULL
;
643 #if defined(ENABLE_WEBRTC)
644 RTCPeerConnectionHandler::DestructAllHandlers();
645 // |peer_connection_factory_| cannot be deleted until after the main message
646 // loop has been destroyed. This is because there may be pending tasks that
647 // hold on to objects produced by the PC factory that depend on threads owned
648 // by the PC factory. Once those tasks have been freed, the factory can be
651 RemoveFilter(vc_manager_
->video_capture_message_filter());
654 RemoveFilter(db_message_filter_
.get());
655 db_message_filter_
= NULL
;
657 // Shutdown the file thread if it's running.
659 file_thread_
->Stop();
661 if (compositor_message_filter_
.get()) {
662 RemoveFilter(compositor_message_filter_
.get());
663 compositor_message_filter_
= NULL
;
666 media_thread_
.reset();
668 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
669 RemoveFilter(audio_message_filter_
.get());
670 audio_message_filter_
= NULL
;
672 compositor_thread_
.reset();
673 input_handler_manager_
.reset();
674 if (input_event_filter_
.get()) {
675 RemoveFilter(input_event_filter_
.get());
676 input_event_filter_
= NULL
;
679 // RemoveEmbeddedWorkerRoute may be called while deleting
680 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
682 embedded_worker_dispatcher_
.reset();
684 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
685 // hold pointers to V8 objects (e.g., via pending requests).
686 main_thread_indexed_db_dispatcher_
.reset();
688 main_thread_compositor_task_runner_
= NULL
;
690 if (gpu_channel_
.get())
691 gpu_channel_
->DestroyChannel();
695 // Clean up plugin channels before this thread goes away.
696 NPChannelBase::CleanupChannels();
699 // Shut down the message loop before shutting down Blink.
700 // This prevents a scenario where a pending task in the message loop accesses
701 // Blink objects after Blink shuts down.
702 // This must be at the very end of the shutdown sequence. You must not touch
703 // the message loop after this.
704 main_message_loop_
.reset();
705 if (blink_platform_impl_
)
708 lazy_tls
.Pointer()->Set(NULL
);
711 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
712 // Certain synchronous messages cannot always be processed synchronously by
713 // the browser, e.g., putting up UI and waiting for the user. This could cause
714 // a complete hang of Chrome if a windowed plug-in is trying to communicate
715 // with the renderer thread since the browser's UI thread could be stuck
716 // (within a Windows API call) trying to synchronously communicate with the
717 // plug-in. The remedy is to pump messages on this thread while the browser
718 // is processing this request. This creates an opportunity for re-entrancy
719 // into WebKit, so we need to take care to disable callbacks, timers, and
720 // pending network loads that could trigger such callbacks.
721 bool pumping_events
= false;
722 if (msg
->is_sync()) {
723 if (msg
->is_caller_pumping_messages()) {
724 pumping_events
= true;
728 bool suspend_webkit_shared_timer
= true; // default value
729 std::swap(suspend_webkit_shared_timer
, suspend_webkit_shared_timer_
);
731 bool notify_webkit_of_modal_loop
= true; // default value
732 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
734 #if defined(ENABLE_PLUGINS)
735 int render_view_id
= MSG_ROUTING_NONE
;
738 if (pumping_events
) {
739 if (suspend_webkit_shared_timer
)
740 blink_platform_impl_
->SuspendSharedTimer();
742 if (notify_webkit_of_modal_loop
)
743 WebView::willEnterModalLoop();
744 #if defined(ENABLE_PLUGINS)
745 RenderViewImpl
* render_view
=
746 RenderViewImpl::FromRoutingID(msg
->routing_id());
748 render_view_id
= msg
->routing_id();
749 PluginChannelHost::Broadcast(
750 new PluginMsg_SignalModalDialogEvent(render_view_id
));
755 bool rv
= ChildThread::Send(msg
);
757 if (pumping_events
) {
758 #if defined(ENABLE_PLUGINS)
759 if (render_view_id
!= MSG_ROUTING_NONE
) {
760 PluginChannelHost::Broadcast(
761 new PluginMsg_ResetModalDialogEvent(render_view_id
));
765 if (notify_webkit_of_modal_loop
)
766 WebView::didExitModalLoop();
768 if (suspend_webkit_shared_timer
)
769 blink_platform_impl_
->ResumeSharedTimer();
775 base::MessageLoop
* RenderThreadImpl::GetMessageLoop() {
776 return message_loop();
779 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
783 std::string
RenderThreadImpl::GetLocale() {
784 // The browser process should have passed the locale to the renderer via the
785 // --lang command line flag.
786 const CommandLine
& parsed_command_line
= *CommandLine::ForCurrentProcess();
787 const std::string
& lang
=
788 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
789 DCHECK(!lang
.empty());
793 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
794 return sync_message_filter();
797 scoped_refptr
<base::MessageLoopProxy
>
798 RenderThreadImpl::GetIOMessageLoopProxy() {
799 return ChildProcess::current()->io_message_loop_proxy();
802 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
803 ChildThread::GetRouter()->AddRoute(routing_id
, listener
);
804 std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
805 pending_render_frame_connects_
.find(routing_id
);
806 if (it
== pending_render_frame_connects_
.end())
809 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(routing_id
);
813 mojo::ScopedMessagePipeHandle
handle(it
->second
);
814 pending_render_frame_connects_
.erase(it
);
815 frame
->BindServiceRegistry(handle
.Pass());
818 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
819 ChildThread::GetRouter()->RemoveRoute(routing_id
);
822 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id
,
823 IPC::Listener
* listener
) {
824 AddRoute(routing_id
, listener
);
825 if (devtools_agent_message_filter_
.get()) {
826 devtools_agent_message_filter_
->AddEmbeddedWorkerRouteOnMainThread(
831 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id
) {
832 RemoveRoute(routing_id
);
833 if (devtools_agent_message_filter_
.get()) {
834 devtools_agent_message_filter_
->RemoveEmbeddedWorkerRouteOnMainThread(
839 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
841 mojo::ScopedMessagePipeHandle handle
) {
842 std::pair
<std::map
<int, mojo::MessagePipeHandle
>::iterator
, bool> result
=
843 pending_render_frame_connects_
.insert(
844 std::make_pair(routing_id
, handle
.release()));
845 CHECK(result
.second
) << "Inserting a duplicate item.";
848 int RenderThreadImpl::GenerateRoutingID() {
849 int routing_id
= MSG_ROUTING_NONE
;
850 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
854 void RenderThreadImpl::AddFilter(IPC::MessageFilter
* filter
) {
855 channel()->AddFilter(filter
);
858 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter
* filter
) {
859 channel()->RemoveFilter(filter
);
862 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
863 observers_
.AddObserver(observer
);
866 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
867 observers_
.RemoveObserver(observer
);
870 void RenderThreadImpl::SetResourceDispatcherDelegate(
871 ResourceDispatcherDelegate
* delegate
) {
872 resource_dispatcher()->set_delegate(delegate
);
875 void RenderThreadImpl::EnsureWebKitInitialized() {
876 if (blink_platform_impl_
)
879 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
881 #ifdef ENABLE_VTUNE_JIT_INTERFACE
882 if (command_line
.HasSwitch(switches::kEnableVtune
))
883 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
886 blink_platform_impl_
.reset(
887 new RendererBlinkPlatformImpl(renderer_scheduler_
.get()));
888 blink::initialize(blink_platform_impl_
.get());
890 v8::Isolate
* isolate
= blink::mainThreadIsolate();
892 isolate
->SetCounterFunction(base::StatsTable::FindLocation
);
893 isolate
->SetCreateHistogramFunction(CreateHistogram
);
894 isolate
->SetAddHistogramSampleFunction(AddHistogramSample
);
896 main_thread_compositor_task_runner_
=
897 renderer_scheduler()->CompositorTaskRunner();
899 bool enable
= !command_line
.HasSwitch(switches::kDisableThreadedCompositing
);
901 #if defined(OS_ANDROID)
902 if (SynchronousCompositorFactory
* factory
=
903 SynchronousCompositorFactory::GetInstance())
904 compositor_message_loop_proxy_
=
905 factory
->GetCompositorMessageLoop();
907 if (!compositor_message_loop_proxy_
.get()) {
908 compositor_thread_
.reset(new base::Thread("Compositor"));
909 compositor_thread_
->Start();
910 #if defined(OS_ANDROID)
911 compositor_thread_
->SetPriority(base::kThreadPriority_Display
);
913 compositor_message_loop_proxy_
=
914 compositor_thread_
->message_loop_proxy();
915 compositor_message_loop_proxy_
->PostTask(
917 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
921 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
922 #if defined(OS_ANDROID)
923 if (SynchronousCompositorFactory
* factory
=
924 SynchronousCompositorFactory::GetInstance()) {
925 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
928 if (!input_handler_manager_client
) {
929 input_event_filter_
=
930 new InputEventFilter(this,
931 main_thread_compositor_task_runner_
,
932 compositor_message_loop_proxy_
);
933 AddFilter(input_event_filter_
.get());
934 input_handler_manager_client
= input_event_filter_
.get();
936 input_handler_manager_
.reset(new InputHandlerManager(
937 compositor_message_loop_proxy_
, input_handler_manager_client
,
938 renderer_scheduler()));
941 scoped_refptr
<base::MessageLoopProxy
> compositor_impl_side_loop
;
943 compositor_impl_side_loop
= compositor_message_loop_proxy_
;
945 compositor_impl_side_loop
= base::MessageLoopProxy::current();
947 compositor_message_filter_
= new CompositorForwardingMessageFilter(
948 compositor_impl_side_loop
.get());
949 AddFilter(compositor_message_filter_
.get());
951 RenderThreadImpl::RegisterSchemes();
953 EnableBlinkPlatformLogChannels(
954 command_line
.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels
));
956 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
958 if (!media::IsMediaLibraryInitialized()) {
959 WebRuntimeFeatures::enableWebAudio(false);
962 RenderMediaClient::Initialize();
964 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
966 devtools_agent_message_filter_
= new DevToolsAgentFilter();
967 AddFilter(devtools_agent_message_filter_
.get());
969 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
970 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
972 cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction
);
974 // Limit use of the scaled image cache to when deferred image decoding is
976 if (!command_line
.HasSwitch(switches::kEnableDeferredImageDecoding
) &&
977 !is_impl_side_painting_enabled_
)
978 SkGraphics::SetResourceCacheTotalByteLimit(0u);
980 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
981 kImageCacheSingleAllocationByteLimit
);
983 if (command_line
.HasSwitch(switches::kMemoryMetrics
)) {
984 memory_observer_
.reset(new MemoryObserver());
985 message_loop()->AddTaskObserver(memory_observer_
.get());
989 void RenderThreadImpl::RegisterSchemes() {
990 // swappedout: pages should not be accessible, and should also
991 // be treated as empty documents that can commit synchronously.
992 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
993 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
994 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
997 void RenderThreadImpl::NotifyTimezoneChange() {
998 NotifyTimezoneChangeOnThisThread();
999 RenderThread::Get()->PostTaskToAllWebWorkers(
1000 base::Bind(&NotifyTimezoneChangeOnThisThread
));
1003 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
1004 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
1007 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
1008 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
1011 scoped_ptr
<base::SharedMemory
>
1012 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
1013 if (size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
1014 return scoped_ptr
<base::SharedMemory
>();
1016 base::SharedMemoryHandle handle
;
1018 IPC::Message
* message
=
1019 new ChildProcessHostMsg_SyncAllocateSharedMemory(size
, &handle
);
1021 // Allow calling this from the compositor thread.
1022 if (base::MessageLoop::current() == message_loop())
1023 success
= ChildThread::Send(message
);
1025 success
= sync_message_filter()->Send(message
);
1028 return scoped_ptr
<base::SharedMemory
>();
1030 if (!base::SharedMemory::IsHandleValid(handle
))
1031 return scoped_ptr
<base::SharedMemory
>();
1033 return scoped_ptr
<base::SharedMemory
>(new base::SharedMemory(handle
, false));
1036 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
1037 WebScriptController::registerExtension(extension
);
1040 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
1041 idle_notification_delay_in_ms_
= initial_delay_ms
;
1043 idle_timer_
.Start(FROM_HERE
,
1044 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
1045 this, &RenderThreadImpl::IdleHandler
);
1048 void RenderThreadImpl::IdleHandler() {
1049 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
1050 GetContentClient()->renderer()->
1051 RunIdleHandlerWhenWidgetsHidden();
1052 if (run_in_foreground_tab
) {
1053 if (idle_notifications_to_skip_
> 0) {
1054 --idle_notifications_to_skip_
;
1056 base::allocator::ReleaseFreeMemory();
1057 base::DiscardableMemory::ReduceMemoryUsage();
1059 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1063 base::allocator::ReleaseFreeMemory();
1064 base::DiscardableMemory::ReleaseFreeMemory();
1066 // Continue the idle timer if the webkit shared timer is not suspended or
1067 // something is left to do.
1068 bool continue_timer
= !webkit_shared_timer_suspended_
;
1070 if (blink::mainThreadIsolate() &&
1071 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1072 continue_timer
= true;
1074 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1075 continue_timer
= true;
1078 // Schedule next invocation. When the tab is originally hidden, an invocation
1079 // is scheduled for kInitialIdleHandlerDelayMs in
1080 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1081 // After that, idle calls can be much less frequent, so run at a maximum of
1082 // once every kLongIdleHandlerDelayMs.
1083 // Dampen the delay using the algorithm (if delay is in seconds):
1084 // delay = delay + 1 / (delay + 2)
1085 // Using floor(delay) has a dampening effect such as:
1086 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1087 // If the delay is in milliseconds, the above formula is equivalent to:
1088 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1089 // which is equivalent to
1090 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1091 if (continue_timer
) {
1092 ScheduleIdleHandler(
1093 std::max(kLongIdleHandlerDelayMs
,
1094 idle_notification_delay_in_ms_
+
1095 1000000 / (idle_notification_delay_in_ms_
+ 2000)));
1101 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
1104 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1105 return idle_notification_delay_in_ms_
;
1108 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1109 int64 idle_notification_delay_in_ms
) {
1110 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
1113 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
1114 child_histogram_message_filter()->SendHistograms(sequence_number
);
1117 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
1118 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure
);
1121 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
1122 bool result
= false;
1123 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
1127 void RenderThreadImpl::PostponeIdleNotification() {
1128 idle_notifications_to_skip_
= 2;
1131 scoped_refptr
<media::GpuVideoAcceleratorFactories
>
1132 RenderThreadImpl::GetGpuFactories() {
1133 DCHECK(IsMainThread());
1135 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
1136 const CommandLine
* cmd_line
= CommandLine::ForCurrentProcess();
1137 scoped_refptr
<media::GpuVideoAcceleratorFactories
> gpu_factories
;
1138 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner
=
1139 GetMediaThreadTaskRunner();
1140 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
1141 if (!gpu_va_context_provider_
.get() ||
1142 gpu_va_context_provider_
->DestroyedOnMainThread()) {
1143 if (!gpu_channel_host
.get()) {
1144 gpu_channel_host
= EstablishGpuChannelSync(
1145 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
1147 blink::WebGraphicsContext3D::Attributes attributes
;
1148 bool lose_context_when_out_of_memory
= false;
1149 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
1151 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1152 gpu_channel_host
.get(),
1154 lose_context_when_out_of_memory
,
1155 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1156 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1158 "GPU-VideoAccelerator-Offscreen");
1161 if (gpu_va_context_provider_
.get()) {
1162 gpu_factories
= RendererGpuVideoAcceleratorFactories::Create(
1163 gpu_channel_host
.get(), media_task_runner
, gpu_va_context_provider_
);
1165 return gpu_factories
;
1168 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
1169 RenderThreadImpl::CreateOffscreenContext3d() {
1170 blink::WebGraphicsContext3D::Attributes
attributes(GetOffscreenAttribs());
1171 bool lose_context_when_out_of_memory
= true;
1173 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
1174 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
1175 return make_scoped_ptr(
1176 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1177 gpu_channel_host
.get(),
1179 lose_context_when_out_of_memory
,
1180 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1181 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1185 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
1186 RenderThreadImpl::SharedMainThreadContextProvider() {
1187 DCHECK(IsMainThread());
1188 if (!shared_main_thread_contexts_
.get() ||
1189 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
1190 shared_main_thread_contexts_
= NULL
;
1191 #if defined(OS_ANDROID)
1192 if (SynchronousCompositorFactory
* factory
=
1193 SynchronousCompositorFactory::GetInstance()) {
1194 shared_main_thread_contexts_
= factory
->CreateOffscreenContextProvider(
1195 GetOffscreenAttribs(), "Offscreen-MainThread");
1198 if (!shared_main_thread_contexts_
.get()) {
1199 shared_main_thread_contexts_
= ContextProviderCommandBuffer::Create(
1200 CreateOffscreenContext3d(), "Offscreen-MainThread");
1202 if (shared_main_thread_contexts_
.get() &&
1203 !shared_main_thread_contexts_
->BindToCurrentThread())
1204 shared_main_thread_contexts_
= NULL
;
1206 return shared_main_thread_contexts_
;
1209 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
1210 if (!audio_renderer_mixer_manager_
) {
1211 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
1212 GetAudioHardwareConfig()));
1215 return audio_renderer_mixer_manager_
.get();
1218 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1219 if (!audio_hardware_config_
) {
1220 media::AudioParameters input_params
;
1221 media::AudioParameters output_params
;
1222 Send(new ViewHostMsg_GetAudioHardwareConfig(
1223 &input_params
, &output_params
));
1225 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1226 input_params
, output_params
));
1227 audio_message_filter_
->SetAudioHardwareConfig(audio_hardware_config_
.get());
1230 return audio_hardware_config_
.get();
1233 base::WaitableEvent
* RenderThreadImpl::GetShutdownEvent() {
1234 return ChildProcess::current()->GetShutDownEvent();
1238 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1239 const base::string16
& str
) {
1240 Send(new ViewHostMsg_PreCacheFontCharacters(log_font
, str
));
1243 void RenderThreadImpl::PreCacheFont(const LOGFONT
& log_font
) {
1244 Send(new ChildProcessHostMsg_PreCacheFont(log_font
));
1247 void RenderThreadImpl::ReleaseCachedFonts() {
1248 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1253 ServiceRegistry
* RenderThreadImpl::GetServiceRegistry() {
1254 return service_registry();
1257 bool RenderThreadImpl::IsMainThread() {
1261 base::MessageLoop
* RenderThreadImpl::GetMainLoop() {
1262 return message_loop();
1265 scoped_refptr
<base::MessageLoopProxy
> RenderThreadImpl::GetIOLoopProxy() {
1266 return io_message_loop_proxy_
;
1269 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1271 return scoped_ptr
<base::SharedMemory
>(
1272 HostAllocateSharedMemoryBuffer(size
));
1275 CreateCommandBufferResult
RenderThreadImpl::CreateViewCommandBuffer(
1277 const GPUCreateCommandBufferConfig
& init_params
,
1280 "RenderThreadImpl::CreateViewCommandBuffer",
1284 CreateCommandBufferResult result
= CREATE_COMMAND_BUFFER_FAILED
;
1285 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1291 // Allow calling this from the compositor thread.
1292 thread_safe_sender()->Send(message
);
1297 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1298 suspend_webkit_shared_timer_
= false;
1301 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1302 notify_webkit_of_modal_loop_
= false;
1305 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1306 ObserverListBase
<RenderProcessObserver
>::Iterator
it(observers_
);
1307 RenderProcessObserver
* observer
;
1308 while ((observer
= it
.GetNext()) != NULL
) {
1309 if (observer
->OnControlMessageReceived(msg
))
1313 // Some messages are handled by delegates.
1314 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1315 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1316 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1320 bool handled
= true;
1321 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1322 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame
, OnCreateNewFrame
)
1323 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy
, OnCreateNewFrameProxy
)
1324 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1325 OnSetZoomLevelForCurrentURL
)
1326 // TODO(port): removed from render_messages_internal.h;
1327 // is there a new non-windows message I should add here?
1328 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1329 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged
, OnNetworkTypeChanged
)
1330 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData
, OnTempCrashWithData
)
1331 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker
, OnCreateNewSharedWorker
)
1332 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1333 #if defined(OS_ANDROID)
1334 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1335 OnSetWebKitSharedTimersSuspended
)
1337 #if defined(OS_MACOSX)
1338 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1340 #if defined(ENABLE_PLUGINS)
1341 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1343 IPC_MESSAGE_UNHANDLED(handled
= false)
1344 IPC_END_MESSAGE_MAP()
1348 void RenderThreadImpl::OnCreateNewFrame(int routing_id
,
1349 int parent_routing_id
,
1350 int proxy_routing_id
) {
1351 RenderFrameImpl::CreateFrame(routing_id
, parent_routing_id
, proxy_routing_id
);
1354 void RenderThreadImpl::OnCreateNewFrameProxy(int routing_id
,
1355 int parent_routing_id
,
1356 int render_view_routing_id
) {
1357 RenderFrameProxy::CreateFrameProxy(
1358 routing_id
, parent_routing_id
, render_view_routing_id
);
1361 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1362 const std::string
& host
,
1363 double zoom_level
) {
1364 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1365 RenderView::ForEach(&zoomer
);
1368 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1369 EnsureWebKitInitialized();
1370 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1371 RenderViewImpl::Create(params
, false);
1374 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1375 CauseForGpuLaunch cause_for_gpu_launch
) {
1376 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1378 if (gpu_channel_
.get()) {
1379 // Do nothing if we already have a GPU channel or are already
1380 // establishing one.
1381 if (!gpu_channel_
->IsLost())
1382 return gpu_channel_
.get();
1384 // Recreate the channel if it has been lost.
1385 gpu_channel_
= NULL
;
1388 // Ask the browser for the channel name.
1390 IPC::ChannelHandle channel_handle
;
1391 gpu::GPUInfo gpu_info
;
1392 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1396 #if defined(OS_POSIX)
1397 channel_handle
.socket
.fd
== -1 ||
1399 channel_handle
.name
.empty()) {
1400 // Otherwise cancel the connection.
1404 GetContentClient()->SetGpuInfo(gpu_info
);
1406 // Cache some variables that are needed on the compositor thread for our
1407 // implementation of GpuChannelHostFactory.
1408 io_message_loop_proxy_
= ChildProcess::current()->io_message_loop_proxy();
1411 GpuChannelHost::Create(this,
1414 ChildProcess::current()->GetShutDownEvent(),
1415 gpu_memory_buffer_manager());
1416 return gpu_channel_
.get();
1419 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1420 blink::WebMediaStreamCenterClient
* client
) {
1421 #if defined(OS_ANDROID)
1422 if (CommandLine::ForCurrentProcess()->HasSwitch(
1423 switches::kDisableWebRTC
))
1427 #if defined(ENABLE_WEBRTC)
1428 if (!media_stream_center_
) {
1429 media_stream_center_
= GetContentClient()->renderer()
1430 ->OverrideCreateWebMediaStreamCenter(client
);
1431 if (!media_stream_center_
) {
1432 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1433 new MediaStreamCenter(client
, GetPeerConnectionDependencyFactory()));
1434 media_stream_center_
= media_stream_center
.release();
1438 return media_stream_center_
;
1441 #if defined(ENABLE_WEBRTC)
1442 PeerConnectionDependencyFactory
*
1443 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1444 return peer_connection_factory_
.get();
1448 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1449 if (!gpu_channel_
.get())
1452 if (gpu_channel_
->IsLost())
1455 return gpu_channel_
.get();
1458 #if defined(ENABLE_PLUGINS)
1459 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1460 EnsureWebKitInitialized();
1461 // The call below will cause a GetPlugins call with refresh=true, but at this
1462 // point we already know that the browser has refreshed its list, so disable
1463 // refresh temporarily to prevent each renderer process causing the list to be
1465 blink_platform_impl_
->set_plugin_refresh_allowed(false);
1466 blink::resetPluginCache(reload_pages
);
1467 blink_platform_impl_
->set_plugin_refresh_allowed(true);
1469 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1473 void RenderThreadImpl::OnNetworkTypeChanged(
1474 net::NetworkChangeNotifier::ConnectionType type
) {
1475 EnsureWebKitInitialized();
1476 bool online
= type
!= net::NetworkChangeNotifier::CONNECTION_NONE
;
1477 WebNetworkStateNotifier::setOnLine(online
);
1479 RenderProcessObserver
, observers_
, NetworkStateChanged(online
));
1480 WebNetworkStateNotifier::setWebConnectionType(
1481 NetConnectionTypeToWebConnectionType(type
));
1484 void RenderThreadImpl::OnTempCrashWithData(const GURL
& data
) {
1485 GetContentClient()->SetActiveURL(data
);
1489 void RenderThreadImpl::OnUpdateTimezone() {
1490 if (!blink_platform_impl_
)
1492 NotifyTimezoneChange();
1495 #if defined(OS_ANDROID)
1496 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1497 if (suspend_webkit_shared_timer_
) {
1498 EnsureWebKitInitialized();
1500 blink_platform_impl_
->SuspendSharedTimer();
1502 blink_platform_impl_
->ResumeSharedTimer();
1504 webkit_shared_timer_suspended_
= suspend
;
1509 #if defined(OS_MACOSX)
1510 void RenderThreadImpl::OnUpdateScrollbarTheme(
1511 float initial_button_delay
,
1512 float autoscroll_button_delay
,
1513 bool jump_on_track_click
,
1514 blink::ScrollerStyle preferred_scroller_style
,
1516 EnsureWebKitInitialized();
1517 static_cast<WebScrollbarBehaviorImpl
*>(
1518 blink_platform_impl_
->scrollbarBehavior())
1519 ->set_jump_on_track_click(jump_on_track_click
);
1520 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay
,
1521 autoscroll_button_delay
,
1522 preferred_scroller_style
,
1527 void RenderThreadImpl::OnCreateNewSharedWorker(
1528 const WorkerProcessMsg_CreateWorker_Params
& params
) {
1529 // EmbeddedSharedWorkerStub will self-destruct.
1530 new EmbeddedSharedWorkerStub(params
.url
,
1532 params
.content_security_policy
,
1533 params
.security_policy_type
,
1534 params
.pause_on_start
,
1538 void RenderThreadImpl::OnMemoryPressure(
1539 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1540 base::allocator::ReleaseFreeMemory();
1542 // Trigger full v8 garbage collection on critical memory notification. This
1543 // will potentially hang the renderer for a long time, however, when we
1544 // receive a memory pressure notification, we might be about to be killed.
1545 if (blink_platform_impl_
&& blink::mainThreadIsolate()) {
1546 blink::mainThreadIsolate()->LowMemoryNotification();
1549 if (memory_pressure_level
==
1550 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
1551 if (blink_platform_impl_
) {
1552 // Clear the image cache. Do not call into blink if it is not initialized.
1553 blink::WebImageCache::clear();
1556 // Purge Skia font cache, by setting it to 0 and then again to the previous
1558 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1559 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1563 scoped_refptr
<base::MessageLoopProxy
>
1564 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1565 DCHECK(message_loop() == base::MessageLoop::current());
1566 if (!file_thread_
) {
1567 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1568 file_thread_
->Start();
1570 return file_thread_
->message_loop_proxy();
1573 scoped_refptr
<base::SingleThreadTaskRunner
>
1574 RenderThreadImpl::GetMediaThreadTaskRunner() {
1575 DCHECK(message_loop() == base::MessageLoop::current());
1576 if (!media_thread_
) {
1577 media_thread_
.reset(new base::Thread("Media"));
1578 media_thread_
->Start();
1580 #if defined(OS_ANDROID)
1581 renderer_demuxer_
= new RendererDemuxerAndroid();
1582 AddFilter(renderer_demuxer_
.get());
1585 return media_thread_
->message_loop_proxy();
1588 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1589 blink_platform_impl_
->sampleGamepads(*data
);
1592 void RenderThreadImpl::WidgetCreated() {
1596 void RenderThreadImpl::WidgetDestroyed() {
1600 void RenderThreadImpl::WidgetHidden() {
1601 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1602 hidden_widget_count_
++;
1604 if (widget_count_
&& hidden_widget_count_
== widget_count_
) {
1605 // TODO(reveman): Remove this when we have a better mechanism to prevent
1606 // total discardable memory used by all renderers from growing too large.
1607 base::internal::DiscardableMemoryEmulated::
1608 ReduceMemoryUsageUntilWithinLimit(
1609 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
);
1611 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1612 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1616 void RenderThreadImpl::WidgetRestored() {
1617 DCHECK_GT(hidden_widget_count_
, 0);
1618 hidden_widget_count_
--;
1620 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1624 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1627 } // namespace content