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/shared_memory.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram.h"
22 #include "base/metrics/stats_table.h"
23 #include "base/path_service.h"
24 #include "base/strings/string16.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_tokenizer.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/threading/thread_local.h"
29 #include "base/threading/thread_restrictions.h"
30 #include "base/values.h"
31 #include "cc/base/switches.h"
32 #include "cc/blink/web_external_bitmap_impl.h"
33 #include "cc/blink/web_layer_impl.h"
34 #include "cc/resources/raster_worker_pool.h"
35 #include "content/child/appcache/appcache_dispatcher.h"
36 #include "content/child/appcache/appcache_frontend_impl.h"
37 #include "content/child/child_histogram_message_filter.h"
38 #include "content/child/content_child_helpers.h"
39 #include "content/child/db_message_filter.h"
40 #include "content/child/indexed_db/indexed_db_dispatcher.h"
41 #include "content/child/indexed_db/indexed_db_message_filter.h"
42 #include "content/child/npapi/npobject_util.h"
43 #include "content/child/plugin_messages.h"
44 #include "content/child/resource_dispatcher.h"
45 #include "content/child/runtime_features.h"
46 #include "content/child/thread_safe_sender.h"
47 #include "content/child/web_database_observer_impl.h"
48 #include "content/child/worker_task_runner.h"
49 #include "content/common/child_process_messages.h"
50 #include "content/common/content_constants_internal.h"
51 #include "content/common/database_messages.h"
52 #include "content/common/dom_storage/dom_storage_messages.h"
53 #include "content/common/frame_messages.h"
54 #include "content/common/gpu/client/context_provider_command_buffer.h"
55 #include "content/common/gpu/client/gpu_channel_host.h"
56 #include "content/common/gpu/client/gpu_memory_buffer_impl.h"
57 #include "content/common/gpu/gpu_messages.h"
58 #include "content/common/gpu/gpu_process_launch_causes.h"
59 #include "content/common/render_frame_setup.mojom.h"
60 #include "content/common/resource_messages.h"
61 #include "content/common/view_messages.h"
62 #include "content/common/worker_messages.h"
63 #include "content/public/common/content_constants.h"
64 #include "content/public/common/content_paths.h"
65 #include "content/public/common/content_switches.h"
66 #include "content/public/common/renderer_preferences.h"
67 #include "content/public/common/url_constants.h"
68 #include "content/public/renderer/content_renderer_client.h"
69 #include "content/public/renderer/render_process_observer.h"
70 #include "content/public/renderer/render_view_visitor.h"
71 #include "content/renderer/devtools/devtools_agent_filter.h"
72 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
73 #include "content/renderer/dom_storage/webstoragearea_impl.h"
74 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
75 #include "content/renderer/gpu/compositor_output_surface.h"
76 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
77 #include "content/renderer/input/input_event_filter.h"
78 #include "content/renderer/input/input_handler_manager.h"
79 #include "content/renderer/media/aec_dump_message_filter.h"
80 #include "content/renderer/media/audio_input_message_filter.h"
81 #include "content/renderer/media/audio_message_filter.h"
82 #include "content/renderer/media/audio_renderer_mixer_manager.h"
83 #include "content/renderer/media/media_stream_center.h"
84 #include "content/renderer/media/midi_message_filter.h"
85 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
86 #include "content/renderer/media/video_capture_impl_manager.h"
87 #include "content/renderer/media/video_capture_message_filter.h"
88 #include "content/renderer/net_info_helper.h"
89 #include "content/renderer/p2p/socket_dispatcher.h"
90 #include "content/renderer/render_frame_proxy.h"
91 #include "content/renderer/render_process_impl.h"
92 #include "content/renderer/render_view_impl.h"
93 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
94 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
95 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
96 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
97 #include "ipc/ipc_channel_handle.h"
98 #include "ipc/ipc_forwarding_message_filter.h"
99 #include "ipc/ipc_platform_file.h"
100 #include "media/base/audio_hardware_config.h"
101 #include "media/base/media.h"
102 #include "media/filters/gpu_video_accelerator_factories.h"
103 #include "mojo/common/common_type_converters.h"
104 #include "net/base/net_errors.h"
105 #include "net/base/net_util.h"
106 #include "skia/ext/event_tracer_impl.h"
107 #include "third_party/WebKit/public/platform/WebString.h"
108 #include "third_party/WebKit/public/web/WebColorName.h"
109 #include "third_party/WebKit/public/web/WebDatabase.h"
110 #include "third_party/WebKit/public/web/WebDocument.h"
111 #include "third_party/WebKit/public/web/WebFrame.h"
112 #include "third_party/WebKit/public/web/WebImageCache.h"
113 #include "third_party/WebKit/public/web/WebKit.h"
114 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
115 #include "third_party/WebKit/public/web/WebPopupMenu.h"
116 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
117 #include "third_party/WebKit/public/web/WebScriptController.h"
118 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
119 #include "third_party/WebKit/public/web/WebView.h"
120 #include "third_party/skia/include/core/SkGraphics.h"
121 #include "ui/base/layout.h"
122 #include "ui/base/ui_base_switches.h"
123 #include "v8/include/v8.h"
125 #if defined(OS_ANDROID)
126 #include <cpu-features.h>
127 #include "content/renderer/android/synchronous_compositor_factory.h"
128 #include "content/renderer/media/android/renderer_demuxer_android.h"
131 #if defined(OS_MACOSX)
132 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
135 #if defined(OS_POSIX)
136 #include "ipc/ipc_channel_posix.h"
144 #include "content/child/npapi/np_channel_base.h"
147 #if defined(ENABLE_PLUGINS)
148 #include "content/renderer/npapi/plugin_channel_host.h"
151 #if defined(ENABLE_WEBRTC)
152 #include "content/renderer/media/peer_connection_tracker.h"
153 #include "content/renderer/media/rtc_peer_connection_handler.h"
154 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
155 #include "content/renderer/media/webrtc_identity_service.h"
158 using base::ThreadRestrictions
;
159 using blink::WebDocument
;
160 using blink::WebFrame
;
161 using blink::WebNetworkStateNotifier
;
162 using blink::WebRuntimeFeatures
;
163 using blink::WebScriptController
;
164 using blink::WebSecurityPolicy
;
165 using blink::WebString
;
166 using blink::WebView
;
172 const int64 kInitialIdleHandlerDelayMs
= 1000;
173 const int64 kShortIdleHandlerDelayMs
= 1000;
174 const int64 kLongIdleHandlerDelayMs
= 30*1000;
175 const int kIdleCPUUsageThresholdInPercents
= 3;
176 const int kMinRasterThreads
= 1;
177 const int kMaxRasterThreads
= 64;
179 // Maximum allocation size allowed for image scaling filters that
180 // require pre-scaling. Skia will fallback to a filter that doesn't
181 // require pre-scaling if the default filter would require an
182 // allocation that exceeds this limit.
183 const size_t kImageCacheSingleAllocationByteLimit
= 64 * 1024 * 1024;
185 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
=
188 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
189 // incorrectly from the wrong thread.
190 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
191 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
193 class RenderViewZoomer
: public RenderViewVisitor
{
195 RenderViewZoomer(const std::string
& scheme
,
196 const std::string
& host
,
197 double zoom_level
) : scheme_(scheme
),
199 zoom_level_(zoom_level
) {
202 virtual bool Visit(RenderView
* render_view
) OVERRIDE
{
203 WebView
* webview
= render_view
->GetWebView();
204 WebDocument document
= webview
->mainFrame()->document();
206 // Don't set zoom level for full-page plugin since they don't use the same
208 if (document
.isPluginDocument())
210 GURL
url(document
.url());
211 // Empty scheme works as wildcard that matches any scheme,
212 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
213 (scheme_
.empty() || scheme_
== url
.scheme()) &&
214 !static_cast<RenderViewImpl
*>(render_view
)
215 ->uses_temporary_zoom_level()) {
216 webview
->hidePopups();
217 webview
->setZoomLevel(zoom_level_
);
223 const std::string scheme_
;
224 const std::string host_
;
225 const double zoom_level_
;
227 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
230 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
231 if (host
== "mail.google.com")
233 if (host
== "docs.google.com" || host
== "drive.google.com")
235 if (host
== "plus.google.com")
237 return std::string();
240 void* CreateHistogram(
241 const char *name
, int min
, int max
, size_t buckets
) {
244 std::string histogram_name
;
245 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
246 if (render_thread_impl
) { // Can be null in tests.
247 histogram_name
= render_thread_impl
->
248 histogram_customizer()->ConvertToCustomHistogramName(name
);
250 histogram_name
= std::string(name
);
252 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
253 histogram_name
, min
, max
, buckets
,
254 base::Histogram::kUmaTargetedHistogramFlag
);
258 void AddHistogramSample(void* hist
, int sample
) {
259 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
260 histogram
->Add(sample
);
263 scoped_ptr
<base::SharedMemory
> AllocateSharedMemoryFunction(size_t size
) {
264 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size
);
267 void EnableBlinkPlatformLogChannels(const std::string
& channels
) {
268 if (channels
.empty())
270 base::StringTokenizer
t(channels
, ", ");
272 blink::enableLogChannel(t
.token().c_str());
275 void NotifyTimezoneChangeOnThisThread() {
276 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
279 v8::Date::DateTimeConfigurationChangeNotification(isolate
);
282 class RenderFrameSetupImpl
: public mojo::InterfaceImpl
<RenderFrameSetup
> {
284 virtual void GetServiceProviderForFrame(
285 int32_t frame_routing_id
,
286 mojo::InterfaceRequest
<mojo::ServiceProvider
> request
) OVERRIDE
{
287 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(frame_routing_id
);
288 // We can receive a GetServiceProviderForFrame message for a frame not yet
289 // created due to a race between the message and a ViewMsg_New IPC that
290 // triggers creation of the RenderFrame we want.
292 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
293 frame_routing_id
, request
.PassMessagePipe());
297 frame
->BindServiceRegistry(request
.PassMessagePipe());
301 void CreateRenderFrameSetup(mojo::InterfaceRequest
<RenderFrameSetup
> request
) {
302 mojo::BindToRequest(new RenderFrameSetupImpl(), &request
);
305 bool ShouldUseMojoChannel() {
306 return CommandLine::ForCurrentProcess()->HasSwitch(
307 switches::kEnableRendererMojoChannel
);
310 blink::WebGraphicsContext3D::Attributes
GetOffscreenAttribs() {
311 blink::WebGraphicsContext3D::Attributes attributes
;
312 attributes
.shareResources
= true;
313 attributes
.depth
= false;
314 attributes
.stencil
= false;
315 attributes
.antialias
= false;
316 attributes
.noAutomaticFlushes
= true;
322 // For measuring memory usage after each task. Behind a command line flag.
323 class MemoryObserver
: public base::MessageLoop::TaskObserver
{
326 virtual ~MemoryObserver() {}
328 virtual void WillProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
331 virtual void DidProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
332 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
336 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
339 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
340 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
341 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
342 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
345 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
347 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
348 const std::string
& host
, size_t view_count
) {
349 if (CommandLine::ForCurrentProcess()->HasSwitch(
350 switches::kDisableHistogramCustomizer
)) {
353 // Check if all RenderViews are displaying a page from the same host. If there
354 // is only one RenderView, the common host is this view's host. If there are
355 // many, check if this one shares the common host of the other
356 // RenderViews. It's ok to not detect some cases where the RenderViews share a
357 // common host. This information is only used for producing custom histograms.
360 else if (host
!= common_host_
)
361 SetCommonHost(std::string());
364 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
365 const char* histogram_name
) const {
366 std::string
name(histogram_name
);
367 if (!common_host_histogram_suffix_
.empty() &&
368 custom_histograms_
.find(name
) != custom_histograms_
.end())
369 name
+= common_host_histogram_suffix_
;
373 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
374 const std::string
& host
) {
375 if (host
!= common_host_
) {
377 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
378 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram
);
382 RenderThreadImpl
* RenderThreadImpl::current() {
383 return lazy_tls
.Pointer()->Get();
386 // When we run plugins in process, we actually run them on the render thread,
387 // which means that we need to make the render thread pump UI events.
388 RenderThreadImpl::RenderThreadImpl()
389 : ChildThread(Options(ShouldUseMojoChannel())) {
393 RenderThreadImpl::RenderThreadImpl(const std::string
& channel_name
)
394 : ChildThread(Options(channel_name
, ShouldUseMojoChannel())) {
398 void RenderThreadImpl::Init() {
399 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
401 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
402 base::PlatformThread::CurrentId(),
403 kTraceEventRendererMainThreadSortIndex
);
405 #if defined(OS_MACOSX) || defined(OS_ANDROID)
406 // On Mac and Android, the select popups are rendered by the browser.
407 blink::WebView::setUseExternalPopupMenus(true);
410 lazy_tls
.Pointer()->Set(this);
412 // Register this object as the main thread.
413 ChildProcess::current()->set_main_thread(this);
415 // In single process the single process is all there is.
416 suspend_webkit_shared_timer_
= true;
417 notify_webkit_of_modal_loop_
= true;
418 webkit_shared_timer_suspended_
= false;
420 hidden_widget_count_
= 0;
421 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
422 idle_notifications_to_skip_
= 0;
423 layout_test_mode_
= false;
425 appcache_dispatcher_
.reset(
426 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
427 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
428 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
429 thread_safe_sender()));
430 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
432 media_stream_center_
= NULL
;
434 db_message_filter_
= new DBMessageFilter();
435 AddFilter(db_message_filter_
.get());
437 vc_manager_
.reset(new VideoCaptureImplManager());
438 AddFilter(vc_manager_
->video_capture_message_filter());
440 #if defined(ENABLE_WEBRTC)
441 peer_connection_tracker_
.reset(new PeerConnectionTracker());
442 AddObserver(peer_connection_tracker_
.get());
444 p2p_socket_dispatcher_
=
445 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
446 AddFilter(p2p_socket_dispatcher_
.get());
448 webrtc_identity_service_
.reset(new WebRTCIdentityService());
450 aec_dump_message_filter_
=
451 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
452 message_loop()->message_loop_proxy());
453 AddFilter(aec_dump_message_filter_
.get());
455 peer_connection_factory_
.reset(new PeerConnectionDependencyFactory(
456 p2p_socket_dispatcher_
.get()));
457 #endif // defined(ENABLE_WEBRTC)
459 audio_input_message_filter_
=
460 new AudioInputMessageFilter(GetIOMessageLoopProxy());
461 AddFilter(audio_input_message_filter_
.get());
463 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
464 AddFilter(audio_message_filter_
.get());
466 midi_message_filter_
= new MidiMessageFilter(GetIOMessageLoopProxy());
467 AddFilter(midi_message_filter_
.get());
469 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
471 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
473 GetContentClient()->renderer()->RenderThreadStarted();
475 InitSkiaEventTracer();
477 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
478 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
479 RegisterExtension(GpuBenchmarkingExtension::Get());
481 is_impl_side_painting_enabled_
=
482 command_line
.HasSwitch(switches::kEnableImplSidePainting
);
483 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
484 is_impl_side_painting_enabled_
);
486 is_zero_copy_enabled_
= command_line
.HasSwitch(switches::kEnableZeroCopy
) &&
487 !command_line
.HasSwitch(switches::kDisableZeroCopy
);
489 is_one_copy_enabled_
= command_line
.HasSwitch(switches::kEnableOneCopy
);
491 if (command_line
.HasSwitch(switches::kDisableLCDText
)) {
492 is_lcd_text_enabled_
= false;
493 } else if (command_line
.HasSwitch(switches::kEnableLCDText
)) {
494 is_lcd_text_enabled_
= true;
496 #if defined(OS_ANDROID)
497 is_lcd_text_enabled_
= false;
499 is_lcd_text_enabled_
= true;
503 is_gpu_rasterization_enabled_
=
504 command_line
.HasSwitch(switches::kEnableGpuRasterization
);
505 is_gpu_rasterization_forced_
=
506 command_line
.HasSwitch(switches::kForceGpuRasterization
);
508 if (command_line
.HasSwitch(switches::kDisableDistanceFieldText
)) {
509 is_distance_field_text_enabled_
= false;
510 } else if (command_line
.HasSwitch(switches::kEnableDistanceFieldText
)) {
511 is_distance_field_text_enabled_
= true;
513 is_distance_field_text_enabled_
= false;
516 is_low_res_tiling_enabled_
= true;
517 if (command_line
.HasSwitch(switches::kDisableLowResTiling
) &&
518 !command_line
.HasSwitch(switches::kEnableLowResTiling
)) {
519 is_low_res_tiling_enabled_
= false;
522 // Note that under Linux, the media library will normally already have
523 // been initialized by the Zygote before this instance became a Renderer.
524 base::FilePath media_path
;
525 PathService::Get(DIR_MEDIA_LIBS
, &media_path
);
526 if (!media_path
.empty())
527 media::InitializeMediaLibrary(media_path
);
529 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
530 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
532 std::vector
<base::DiscardableMemoryType
> supported_types
;
533 base::DiscardableMemory::GetSupportedTypes(&supported_types
);
534 DCHECK(!supported_types
.empty());
536 // The default preferred type is always the first one in list.
537 base::DiscardableMemoryType type
= supported_types
[0];
539 if (command_line
.HasSwitch(switches::kUseDiscardableMemory
)) {
540 std::string requested_type_name
= command_line
.GetSwitchValueASCII(
541 switches::kUseDiscardableMemory
);
542 base::DiscardableMemoryType requested_type
=
543 base::DiscardableMemory::GetNamedType(requested_type_name
);
544 if (std::find(supported_types
.begin(),
545 supported_types
.end(),
546 requested_type
) != supported_types
.end()) {
547 type
= requested_type
;
549 LOG(ERROR
) << "Requested discardable memory type is not supported.";
553 base::DiscardableMemory::SetPreferredType(type
);
555 // AllocateGpuMemoryBuffer must be used exclusively on one thread but
556 // it doesn't have to be the same thread RenderThreadImpl is created on.
557 allocate_gpu_memory_buffer_thread_checker_
.DetachFromThread();
559 if (command_line
.HasSwitch(switches::kNumRasterThreads
)) {
560 int num_raster_threads
;
561 std::string string_value
=
562 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
563 if (base::StringToInt(string_value
, &num_raster_threads
) &&
564 num_raster_threads
>= kMinRasterThreads
&&
565 num_raster_threads
<= kMaxRasterThreads
) {
566 cc::RasterWorkerPool::SetNumRasterThreads(num_raster_threads
);
568 LOG(WARNING
) << "Failed to parse switch " <<
569 switches::kNumRasterThreads
<< ": " << string_value
;
573 service_registry()->AddService
<RenderFrameSetup
>(
574 base::Bind(CreateRenderFrameSetup
));
576 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
579 RenderThreadImpl::~RenderThreadImpl() {
580 for (std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
581 pending_render_frame_connects_
.begin();
582 it
!= pending_render_frame_connects_
.end();
584 mojo::CloseRaw(it
->second
);
588 void RenderThreadImpl::Shutdown() {
590 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
592 ChildThread::Shutdown();
594 if (memory_observer_
) {
595 message_loop()->RemoveTaskObserver(memory_observer_
.get());
596 memory_observer_
.reset();
599 // Wait for all databases to be closed.
600 if (webkit_platform_support_
) {
601 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
602 // processing timer events while we're already in the process of shutting
603 // down blink, put a ScopePageLoadDeferrer on the stack.
604 WebView::willEnterModalLoop();
605 webkit_platform_support_
->web_database_observer_impl()->
606 WaitForAllDatabasesToClose();
607 WebView::didExitModalLoop();
610 // Shutdown in reverse of the initialization order.
611 if (devtools_agent_message_filter_
.get()) {
612 RemoveFilter(devtools_agent_message_filter_
.get());
613 devtools_agent_message_filter_
= NULL
;
616 RemoveFilter(audio_input_message_filter_
.get());
617 audio_input_message_filter_
= NULL
;
619 RemoveFilter(audio_message_filter_
.get());
620 audio_message_filter_
= NULL
;
622 #if defined(ENABLE_WEBRTC)
623 RTCPeerConnectionHandler::DestructAllHandlers();
625 peer_connection_factory_
.reset();
627 RemoveFilter(vc_manager_
->video_capture_message_filter());
630 RemoveFilter(db_message_filter_
.get());
631 db_message_filter_
= NULL
;
633 // Shutdown the file thread if it's running.
635 file_thread_
->Stop();
637 if (compositor_output_surface_filter_
.get()) {
638 RemoveFilter(compositor_output_surface_filter_
.get());
639 compositor_output_surface_filter_
= NULL
;
642 media_thread_
.reset();
643 compositor_thread_
.reset();
644 input_handler_manager_
.reset();
645 if (input_event_filter_
.get()) {
646 RemoveFilter(input_event_filter_
.get());
647 input_event_filter_
= NULL
;
650 // RemoveEmbeddedWorkerRoute may be called while deleting
651 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
653 embedded_worker_dispatcher_
.reset();
655 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
656 // hold pointers to V8 objects (e.g., via pending requests).
657 main_thread_indexed_db_dispatcher_
.reset();
659 if (webkit_platform_support_
)
662 lazy_tls
.Pointer()->Set(NULL
);
666 // Clean up plugin channels before this thread goes away.
667 NPChannelBase::CleanupChannels();
671 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
672 // Certain synchronous messages cannot always be processed synchronously by
673 // the browser, e.g., putting up UI and waiting for the user. This could cause
674 // a complete hang of Chrome if a windowed plug-in is trying to communicate
675 // with the renderer thread since the browser's UI thread could be stuck
676 // (within a Windows API call) trying to synchronously communicate with the
677 // plug-in. The remedy is to pump messages on this thread while the browser
678 // is processing this request. This creates an opportunity for re-entrancy
679 // into WebKit, so we need to take care to disable callbacks, timers, and
680 // pending network loads that could trigger such callbacks.
681 bool pumping_events
= false;
682 if (msg
->is_sync()) {
683 if (msg
->is_caller_pumping_messages()) {
684 pumping_events
= true;
688 bool suspend_webkit_shared_timer
= true; // default value
689 std::swap(suspend_webkit_shared_timer
, suspend_webkit_shared_timer_
);
691 bool notify_webkit_of_modal_loop
= true; // default value
692 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
694 #if defined(ENABLE_PLUGINS)
695 int render_view_id
= MSG_ROUTING_NONE
;
698 if (pumping_events
) {
699 if (suspend_webkit_shared_timer
)
700 webkit_platform_support_
->SuspendSharedTimer();
702 if (notify_webkit_of_modal_loop
)
703 WebView::willEnterModalLoop();
704 #if defined(ENABLE_PLUGINS)
705 RenderViewImpl
* render_view
=
706 RenderViewImpl::FromRoutingID(msg
->routing_id());
708 render_view_id
= msg
->routing_id();
709 PluginChannelHost::Broadcast(
710 new PluginMsg_SignalModalDialogEvent(render_view_id
));
715 bool rv
= ChildThread::Send(msg
);
717 if (pumping_events
) {
718 #if defined(ENABLE_PLUGINS)
719 if (render_view_id
!= MSG_ROUTING_NONE
) {
720 PluginChannelHost::Broadcast(
721 new PluginMsg_ResetModalDialogEvent(render_view_id
));
725 if (notify_webkit_of_modal_loop
)
726 WebView::didExitModalLoop();
728 if (suspend_webkit_shared_timer
)
729 webkit_platform_support_
->ResumeSharedTimer();
735 base::MessageLoop
* RenderThreadImpl::GetMessageLoop() {
736 return message_loop();
739 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
743 std::string
RenderThreadImpl::GetLocale() {
744 // The browser process should have passed the locale to the renderer via the
745 // --lang command line flag.
746 const CommandLine
& parsed_command_line
= *CommandLine::ForCurrentProcess();
747 const std::string
& lang
=
748 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
749 DCHECK(!lang
.empty());
753 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
754 return sync_message_filter();
757 scoped_refptr
<base::MessageLoopProxy
>
758 RenderThreadImpl::GetIOMessageLoopProxy() {
759 return ChildProcess::current()->io_message_loop_proxy();
762 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
763 ChildThread::GetRouter()->AddRoute(routing_id
, listener
);
764 std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
765 pending_render_frame_connects_
.find(routing_id
);
766 if (it
== pending_render_frame_connects_
.end())
769 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(routing_id
);
773 mojo::ScopedMessagePipeHandle
handle(it
->second
);
774 pending_render_frame_connects_
.erase(it
);
775 frame
->BindServiceRegistry(handle
.Pass());
778 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
779 ChildThread::GetRouter()->RemoveRoute(routing_id
);
782 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id
,
783 IPC::Listener
* listener
) {
784 AddRoute(routing_id
, listener
);
785 if (devtools_agent_message_filter_
.get()) {
786 devtools_agent_message_filter_
->AddEmbeddedWorkerRouteOnMainThread(
791 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id
) {
792 RemoveRoute(routing_id
);
793 if (devtools_agent_message_filter_
.get()) {
794 devtools_agent_message_filter_
->RemoveEmbeddedWorkerRouteOnMainThread(
799 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
801 mojo::ScopedMessagePipeHandle handle
) {
802 std::pair
<std::map
<int, mojo::MessagePipeHandle
>::iterator
, bool> result
=
803 pending_render_frame_connects_
.insert(
804 std::make_pair(routing_id
, handle
.release()));
805 CHECK(result
.second
) << "Inserting a duplicate item.";
808 int RenderThreadImpl::GenerateRoutingID() {
809 int routing_id
= MSG_ROUTING_NONE
;
810 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
814 void RenderThreadImpl::AddFilter(IPC::MessageFilter
* filter
) {
815 channel()->AddFilter(filter
);
818 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter
* filter
) {
819 channel()->RemoveFilter(filter
);
822 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
823 observers_
.AddObserver(observer
);
826 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
827 observers_
.RemoveObserver(observer
);
830 void RenderThreadImpl::SetResourceDispatcherDelegate(
831 ResourceDispatcherDelegate
* delegate
) {
832 resource_dispatcher()->set_delegate(delegate
);
835 void RenderThreadImpl::EnsureWebKitInitialized() {
836 if (webkit_platform_support_
)
839 webkit_platform_support_
.reset(new RendererWebKitPlatformSupportImpl
);
840 blink::initialize(webkit_platform_support_
.get());
842 v8::Isolate
* isolate
= blink::mainThreadIsolate();
844 isolate
->SetCounterFunction(base::StatsTable::FindLocation
);
845 isolate
->SetCreateHistogramFunction(CreateHistogram
);
846 isolate
->SetAddHistogramSampleFunction(AddHistogramSample
);
848 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
850 bool enable
= !command_line
.HasSwitch(switches::kDisableThreadedCompositing
);
852 #if defined(OS_ANDROID)
853 if (SynchronousCompositorFactory
* factory
=
854 SynchronousCompositorFactory::GetInstance())
855 compositor_message_loop_proxy_
=
856 factory
->GetCompositorMessageLoop();
858 if (!compositor_message_loop_proxy_
.get()) {
859 compositor_thread_
.reset(new base::Thread("Compositor"));
860 compositor_thread_
->Start();
861 #if defined(OS_ANDROID)
862 compositor_thread_
->SetPriority(base::kThreadPriority_Display
);
864 compositor_message_loop_proxy_
=
865 compositor_thread_
->message_loop_proxy();
866 compositor_message_loop_proxy_
->PostTask(
868 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
872 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
873 #if defined(OS_ANDROID)
874 if (SynchronousCompositorFactory
* factory
=
875 SynchronousCompositorFactory::GetInstance()) {
876 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
879 if (!input_handler_manager_client
) {
880 input_event_filter_
=
881 new InputEventFilter(this, compositor_message_loop_proxy_
);
882 AddFilter(input_event_filter_
.get());
883 input_handler_manager_client
= input_event_filter_
.get();
885 input_handler_manager_
.reset(
886 new InputHandlerManager(compositor_message_loop_proxy_
,
887 input_handler_manager_client
));
890 scoped_refptr
<base::MessageLoopProxy
> output_surface_loop
;
892 output_surface_loop
= compositor_message_loop_proxy_
;
894 output_surface_loop
= base::MessageLoopProxy::current();
896 compositor_output_surface_filter_
=
897 CompositorOutputSurface::CreateFilter(output_surface_loop
.get());
898 AddFilter(compositor_output_surface_filter_
.get());
900 RenderThreadImpl::RegisterSchemes();
902 EnableBlinkPlatformLogChannels(
903 command_line
.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels
));
905 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
907 if (!media::IsMediaLibraryInitialized()) {
908 WebRuntimeFeatures::enableMediaPlayer(false);
909 WebRuntimeFeatures::enableWebAudio(false);
912 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
914 devtools_agent_message_filter_
= new DevToolsAgentFilter();
915 AddFilter(devtools_agent_message_filter_
.get());
917 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
918 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
920 cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction
);
922 // Limit use of the scaled image cache to when deferred image decoding is
924 if (!command_line
.HasSwitch(switches::kEnableDeferredImageDecoding
) &&
925 !is_impl_side_painting_enabled_
)
926 SkGraphics::SetImageCacheByteLimit(0u);
928 SkGraphics::SetImageCacheSingleAllocationByteLimit(
929 kImageCacheSingleAllocationByteLimit
);
931 if (command_line
.HasSwitch(switches::kMemoryMetrics
)) {
932 memory_observer_
.reset(new MemoryObserver());
933 message_loop()->AddTaskObserver(memory_observer_
.get());
937 void RenderThreadImpl::RegisterSchemes() {
938 // swappedout: pages should not be accessible, and should also
939 // be treated as empty documents that can commit synchronously.
940 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
941 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
942 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
945 void RenderThreadImpl::NotifyTimezoneChange() {
946 NotifyTimezoneChangeOnThisThread();
947 RenderThread::Get()->PostTaskToAllWebWorkers(
948 base::Bind(&NotifyTimezoneChangeOnThisThread
));
951 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
952 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
955 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
956 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
959 scoped_ptr
<base::SharedMemory
>
960 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
961 if (size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
962 return scoped_ptr
<base::SharedMemory
>();
964 base::SharedMemoryHandle handle
;
966 IPC::Message
* message
=
967 new ChildProcessHostMsg_SyncAllocateSharedMemory(size
, &handle
);
969 // Allow calling this from the compositor thread.
970 if (base::MessageLoop::current() == message_loop())
971 success
= ChildThread::Send(message
);
973 success
= sync_message_filter()->Send(message
);
976 return scoped_ptr
<base::SharedMemory
>();
978 if (!base::SharedMemory::IsHandleValid(handle
))
979 return scoped_ptr
<base::SharedMemory
>();
981 return scoped_ptr
<base::SharedMemory
>(new base::SharedMemory(handle
, false));
984 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
985 WebScriptController::registerExtension(extension
);
988 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
989 idle_notification_delay_in_ms_
= initial_delay_ms
;
991 idle_timer_
.Start(FROM_HERE
,
992 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
993 this, &RenderThreadImpl::IdleHandler
);
996 void RenderThreadImpl::IdleHandler() {
997 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
998 GetContentClient()->renderer()->
999 RunIdleHandlerWhenWidgetsHidden();
1000 if (run_in_foreground_tab
) {
1001 IdleHandlerInForegroundTab();
1005 base::allocator::ReleaseFreeMemory();
1007 // Continue the idle timer if the webkit shared timer is not suspended or
1008 // something is left to do.
1009 bool continue_timer
= !webkit_shared_timer_suspended_
;
1011 if (blink::mainThreadIsolate() &&
1012 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1013 continue_timer
= true;
1015 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1016 continue_timer
= true;
1019 // Schedule next invocation.
1020 // Dampen the delay using the algorithm (if delay is in seconds):
1021 // delay = delay + 1 / (delay + 2)
1022 // Using floor(delay) has a dampening effect such as:
1023 // 1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
1024 // If the delay is in milliseconds, the above formula is equivalent to:
1025 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1026 // which is equivalent to
1027 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1028 // Note that idle_notification_delay_in_ms_ would be reset to
1029 // kInitialIdleHandlerDelayMs in RenderThreadImpl::WidgetHidden.
1030 if (continue_timer
) {
1031 ScheduleIdleHandler(idle_notification_delay_in_ms_
+
1032 1000000 / (idle_notification_delay_in_ms_
+ 2000));
1038 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
1041 void RenderThreadImpl::IdleHandlerInForegroundTab() {
1042 // Increase the delay in the same way as in IdleHandler,
1043 // but make it periodic by reseting it once it is too big.
1044 int64 new_delay_ms
= idle_notification_delay_in_ms_
+
1045 1000000 / (idle_notification_delay_in_ms_
+ 2000);
1046 if (new_delay_ms
>= kLongIdleHandlerDelayMs
)
1047 new_delay_ms
= kShortIdleHandlerDelayMs
;
1049 if (idle_notifications_to_skip_
> 0) {
1050 idle_notifications_to_skip_
--;
1053 Send(new ViewHostMsg_GetCPUUsage(&cpu_usage
));
1054 // Idle notification hint roughly specifies the expected duration of the
1055 // idle pause. We set it proportional to the idle timer delay.
1056 int idle_hint
= static_cast<int>(new_delay_ms
/ 10);
1057 if (cpu_usage
< kIdleCPUUsageThresholdInPercents
) {
1058 base::allocator::ReleaseFreeMemory();
1060 bool finished_idle_work
= true;
1061 if (blink::mainThreadIsolate() &&
1062 !blink::mainThreadIsolate()->IdleNotification(idle_hint
)) {
1063 finished_idle_work
= false;
1065 if (!base::DiscardableMemory::ReduceMemoryUsage())
1066 finished_idle_work
= false;
1068 // V8 finished collecting garbage and discardable memory system has no
1069 // more idle work left.
1070 if (finished_idle_work
)
1071 new_delay_ms
= kLongIdleHandlerDelayMs
;
1074 ScheduleIdleHandler(new_delay_ms
);
1077 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1078 return idle_notification_delay_in_ms_
;
1081 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1082 int64 idle_notification_delay_in_ms
) {
1083 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
1086 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
1087 child_histogram_message_filter()->SendHistograms(sequence_number
);
1090 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
1091 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure
);
1094 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
1095 bool result
= false;
1096 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
1100 void RenderThreadImpl::PostponeIdleNotification() {
1101 idle_notifications_to_skip_
= 2;
1104 scoped_refptr
<media::GpuVideoAcceleratorFactories
>
1105 RenderThreadImpl::GetGpuFactories() {
1106 DCHECK(IsMainThread());
1108 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
1109 const CommandLine
* cmd_line
= CommandLine::ForCurrentProcess();
1110 scoped_refptr
<media::GpuVideoAcceleratorFactories
> gpu_factories
;
1111 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner
=
1112 GetMediaThreadTaskRunner();
1113 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
1114 if (!gpu_va_context_provider_
.get() ||
1115 gpu_va_context_provider_
->DestroyedOnMainThread()) {
1116 if (!gpu_channel_host
.get()) {
1117 gpu_channel_host
= EstablishGpuChannelSync(
1118 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
1120 blink::WebGraphicsContext3D::Attributes attributes
;
1121 bool lose_context_when_out_of_memory
= false;
1122 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
1124 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1125 gpu_channel_host
.get(),
1127 lose_context_when_out_of_memory
,
1128 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1129 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1131 "GPU-VideoAccelerator-Offscreen");
1134 if (gpu_va_context_provider_
.get()) {
1135 gpu_factories
= RendererGpuVideoAcceleratorFactories::Create(
1136 gpu_channel_host
.get(), media_task_runner
, gpu_va_context_provider_
);
1138 return gpu_factories
;
1141 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
1142 RenderThreadImpl::CreateOffscreenContext3d() {
1143 blink::WebGraphicsContext3D::Attributes
attributes(GetOffscreenAttribs());
1144 bool lose_context_when_out_of_memory
= true;
1146 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
1147 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
1148 return make_scoped_ptr(
1149 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1150 gpu_channel_host
.get(),
1152 lose_context_when_out_of_memory
,
1153 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1154 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1158 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
1159 RenderThreadImpl::SharedMainThreadContextProvider() {
1160 DCHECK(IsMainThread());
1161 if (!shared_main_thread_contexts_
.get() ||
1162 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
1163 shared_main_thread_contexts_
= NULL
;
1164 #if defined(OS_ANDROID)
1165 if (SynchronousCompositorFactory
* factory
=
1166 SynchronousCompositorFactory::GetInstance()) {
1167 shared_main_thread_contexts_
= factory
->CreateOffscreenContextProvider(
1168 GetOffscreenAttribs(), "Offscreen-MainThread");
1171 if (!shared_main_thread_contexts_
.get()) {
1172 shared_main_thread_contexts_
= ContextProviderCommandBuffer::Create(
1173 CreateOffscreenContext3d(), "Offscreen-MainThread");
1175 if (shared_main_thread_contexts_
.get() &&
1176 !shared_main_thread_contexts_
->BindToCurrentThread())
1177 shared_main_thread_contexts_
= NULL
;
1179 return shared_main_thread_contexts_
;
1182 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
1183 if (!audio_renderer_mixer_manager_
) {
1184 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
1185 GetAudioHardwareConfig()));
1188 return audio_renderer_mixer_manager_
.get();
1191 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1192 if (!audio_hardware_config_
) {
1193 media::AudioParameters input_params
;
1194 media::AudioParameters output_params
;
1195 Send(new ViewHostMsg_GetAudioHardwareConfig(
1196 &input_params
, &output_params
));
1198 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1199 input_params
, output_params
));
1200 audio_message_filter_
->SetAudioHardwareConfig(audio_hardware_config_
.get());
1203 return audio_hardware_config_
.get();
1206 base::WaitableEvent
* RenderThreadImpl::GetShutdownEvent() {
1207 return ChildProcess::current()->GetShutDownEvent();
1211 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1212 const base::string16
& str
) {
1213 Send(new ViewHostMsg_PreCacheFontCharacters(log_font
, str
));
1216 void RenderThreadImpl::PreCacheFont(const LOGFONT
& log_font
) {
1217 Send(new ChildProcessHostMsg_PreCacheFont(log_font
));
1220 void RenderThreadImpl::ReleaseCachedFonts() {
1221 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1226 ServiceRegistry
* RenderThreadImpl::GetServiceRegistry() {
1227 return service_registry();
1230 bool RenderThreadImpl::IsMainThread() {
1234 base::MessageLoop
* RenderThreadImpl::GetMainLoop() {
1235 return message_loop();
1238 scoped_refptr
<base::MessageLoopProxy
> RenderThreadImpl::GetIOLoopProxy() {
1239 return io_message_loop_proxy_
;
1242 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1244 return scoped_ptr
<base::SharedMemory
>(
1245 HostAllocateSharedMemoryBuffer(size
));
1248 CreateCommandBufferResult
RenderThreadImpl::CreateViewCommandBuffer(
1250 const GPUCreateCommandBufferConfig
& init_params
,
1253 "RenderThreadImpl::CreateViewCommandBuffer",
1257 CreateCommandBufferResult result
= CREATE_COMMAND_BUFFER_FAILED
;
1258 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1264 // Allow calling this from the compositor thread.
1265 thread_safe_sender()->Send(message
);
1270 scoped_ptr
<gfx::GpuMemoryBuffer
> RenderThreadImpl::AllocateGpuMemoryBuffer(
1273 unsigned internalformat
,
1275 DCHECK(allocate_gpu_memory_buffer_thread_checker_
.CalledOnValidThread());
1277 if (!GpuMemoryBufferImpl::IsFormatValid(internalformat
))
1278 return scoped_ptr
<gfx::GpuMemoryBuffer
>();
1280 gfx::GpuMemoryBufferHandle handle
;
1282 IPC::Message
* message
= new ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer(
1283 width
, height
, internalformat
, usage
, &handle
);
1285 // Allow calling this from the compositor thread.
1286 if (base::MessageLoop::current() == message_loop())
1287 success
= ChildThread::Send(message
);
1289 success
= sync_message_filter()->Send(message
);
1292 return scoped_ptr
<gfx::GpuMemoryBuffer
>();
1294 return GpuMemoryBufferImpl::CreateFromHandle(
1295 handle
, gfx::Size(width
, height
), internalformat
)
1296 .PassAs
<gfx::GpuMemoryBuffer
>();
1299 void RenderThreadImpl::DeleteGpuMemoryBuffer(
1300 scoped_ptr
<gfx::GpuMemoryBuffer
> buffer
) {
1301 gfx::GpuMemoryBufferHandle
handle(buffer
->GetHandle());
1303 IPC::Message
* message
= new ChildProcessHostMsg_DeletedGpuMemoryBuffer(
1304 handle
.type
, handle
.global_id
);
1306 // Allow calling this from the compositor thread.
1307 thread_safe_sender()->Send(message
);
1310 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1311 suspend_webkit_shared_timer_
= false;
1314 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1315 notify_webkit_of_modal_loop_
= false;
1318 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1319 ObserverListBase
<RenderProcessObserver
>::Iterator
it(observers_
);
1320 RenderProcessObserver
* observer
;
1321 while ((observer
= it
.GetNext()) != NULL
) {
1322 if (observer
->OnControlMessageReceived(msg
))
1326 // Some messages are handled by delegates.
1327 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1328 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1329 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1333 bool handled
= true;
1334 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1335 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame
, OnCreateNewFrame
)
1336 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy
, OnCreateNewFrameProxy
)
1337 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1338 OnSetZoomLevelForCurrentURL
)
1339 // TODO(port): removed from render_messages_internal.h;
1340 // is there a new non-windows message I should add here?
1341 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1342 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1343 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged
, OnNetworkTypeChanged
)
1344 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData
, OnTempCrashWithData
)
1345 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker
, OnCreateNewSharedWorker
)
1346 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1347 #if defined(OS_ANDROID)
1348 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1349 OnSetWebKitSharedTimersSuspended
)
1351 #if defined(OS_MACOSX)
1352 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1354 IPC_MESSAGE_UNHANDLED(handled
= false)
1355 IPC_END_MESSAGE_MAP()
1359 void RenderThreadImpl::OnCreateNewFrame(int routing_id
, int parent_routing_id
) {
1360 RenderFrameImpl::CreateFrame(routing_id
, parent_routing_id
);
1363 void RenderThreadImpl::OnCreateNewFrameProxy(int routing_id
,
1364 int parent_routing_id
,
1365 int render_view_routing_id
) {
1366 RenderFrameProxy::CreateFrameProxy(
1367 routing_id
, parent_routing_id
, render_view_routing_id
);
1370 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1371 const std::string
& host
,
1372 double zoom_level
) {
1373 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1374 RenderView::ForEach(&zoomer
);
1377 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1378 EnsureWebKitInitialized();
1379 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1380 RenderViewImpl::Create(params
.opener_route_id
,
1381 params
.window_was_created_with_opener
,
1382 params
.renderer_preferences
,
1383 params
.web_preferences
,
1385 params
.main_frame_routing_id
,
1387 params
.session_storage_namespace_id
,
1391 params
.proxy_routing_id
,
1393 params
.never_visible
,
1394 params
.next_page_id
,
1395 params
.screen_info
);
1398 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1399 CauseForGpuLaunch cause_for_gpu_launch
) {
1400 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1402 if (gpu_channel_
.get()) {
1403 // Do nothing if we already have a GPU channel or are already
1404 // establishing one.
1405 if (!gpu_channel_
->IsLost())
1406 return gpu_channel_
.get();
1408 // Recreate the channel if it has been lost.
1409 gpu_channel_
= NULL
;
1412 // Ask the browser for the channel name.
1414 IPC::ChannelHandle channel_handle
;
1415 gpu::GPUInfo gpu_info
;
1416 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1420 #if defined(OS_POSIX)
1421 channel_handle
.socket
.fd
== -1 ||
1423 channel_handle
.name
.empty()) {
1424 // Otherwise cancel the connection.
1428 GetContentClient()->SetGpuInfo(gpu_info
);
1430 // Cache some variables that are needed on the compositor thread for our
1431 // implementation of GpuChannelHostFactory.
1432 io_message_loop_proxy_
= ChildProcess::current()->io_message_loop_proxy();
1434 gpu_channel_
= GpuChannelHost::Create(
1435 this, gpu_info
, channel_handle
,
1436 ChildProcess::current()->GetShutDownEvent());
1437 return gpu_channel_
.get();
1440 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1441 blink::WebMediaStreamCenterClient
* client
) {
1442 #if defined(OS_ANDROID)
1443 if (CommandLine::ForCurrentProcess()->HasSwitch(
1444 switches::kDisableWebRTC
))
1448 #if defined(ENABLE_WEBRTC)
1449 if (!media_stream_center_
) {
1450 media_stream_center_
= GetContentClient()->renderer()
1451 ->OverrideCreateWebMediaStreamCenter(client
);
1452 if (!media_stream_center_
) {
1453 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1454 new MediaStreamCenter(client
, GetPeerConnectionDependencyFactory()));
1455 AddObserver(media_stream_center
.get());
1456 media_stream_center_
= media_stream_center
.release();
1460 return media_stream_center_
;
1463 #if defined(ENABLE_WEBRTC)
1464 PeerConnectionDependencyFactory
*
1465 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1466 return peer_connection_factory_
.get();
1470 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1471 if (!gpu_channel_
.get())
1474 if (gpu_channel_
->IsLost())
1477 return gpu_channel_
.get();
1480 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1481 EnsureWebKitInitialized();
1482 // The call below will cause a GetPlugins call with refresh=true, but at this
1483 // point we already know that the browser has refreshed its list, so disable
1484 // refresh temporarily to prevent each renderer process causing the list to be
1486 webkit_platform_support_
->set_plugin_refresh_allowed(false);
1487 blink::resetPluginCache(reload_pages
);
1488 webkit_platform_support_
->set_plugin_refresh_allowed(true);
1490 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1493 void RenderThreadImpl::OnNetworkTypeChanged(
1494 net::NetworkChangeNotifier::ConnectionType type
) {
1495 EnsureWebKitInitialized();
1496 bool online
= type
!= net::NetworkChangeNotifier::CONNECTION_NONE
;
1497 WebNetworkStateNotifier::setOnLine(online
);
1499 RenderProcessObserver
, observers_
, NetworkStateChanged(online
));
1500 WebNetworkStateNotifier::setWebConnectionType(
1501 NetConnectionTypeToWebConnectionType(type
));
1504 void RenderThreadImpl::OnTempCrashWithData(const GURL
& data
) {
1505 GetContentClient()->SetActiveURL(data
);
1509 void RenderThreadImpl::OnUpdateTimezone() {
1510 NotifyTimezoneChange();
1513 #if defined(OS_ANDROID)
1514 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1515 if (suspend_webkit_shared_timer_
) {
1516 EnsureWebKitInitialized();
1518 webkit_platform_support_
->SuspendSharedTimer();
1520 webkit_platform_support_
->ResumeSharedTimer();
1522 webkit_shared_timer_suspended_
= suspend
;
1527 #if defined(OS_MACOSX)
1528 void RenderThreadImpl::OnUpdateScrollbarTheme(
1529 float initial_button_delay
,
1530 float autoscroll_button_delay
,
1531 bool jump_on_track_click
,
1532 blink::ScrollerStyle preferred_scroller_style
,
1534 EnsureWebKitInitialized();
1535 static_cast<WebScrollbarBehaviorImpl
*>(
1536 webkit_platform_support_
->scrollbarBehavior())->set_jump_on_track_click(
1537 jump_on_track_click
);
1538 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay
,
1539 autoscroll_button_delay
,
1540 preferred_scroller_style
,
1545 void RenderThreadImpl::OnCreateNewSharedWorker(
1546 const WorkerProcessMsg_CreateWorker_Params
& params
) {
1547 // EmbeddedSharedWorkerStub will self-destruct.
1548 new EmbeddedSharedWorkerStub(params
.url
,
1550 params
.content_security_policy
,
1551 params
.security_policy_type
,
1552 params
.pause_on_start
,
1556 void RenderThreadImpl::OnMemoryPressure(
1557 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1558 base::allocator::ReleaseFreeMemory();
1560 // Trigger full v8 garbage collection on critical memory notification. This
1561 // will potentially hang the renderer for a long time, however, when we
1562 // receive a memory pressure notification, we might be about to be killed.
1563 if (webkit_platform_support_
&& blink::mainThreadIsolate()) {
1564 blink::mainThreadIsolate()->LowMemoryNotification();
1567 if (memory_pressure_level
==
1568 base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL
) {
1569 if (webkit_platform_support_
) {
1570 // Clear the image cache. Do not call into blink if it is not initialized.
1571 blink::WebImageCache::clear();
1574 // Purge Skia font cache, by setting it to 0 and then again to the previous
1576 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1577 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1581 scoped_refptr
<base::MessageLoopProxy
>
1582 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1583 DCHECK(message_loop() == base::MessageLoop::current());
1584 if (!file_thread_
) {
1585 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1586 file_thread_
->Start();
1588 return file_thread_
->message_loop_proxy();
1591 scoped_refptr
<base::SingleThreadTaskRunner
>
1592 RenderThreadImpl::GetMediaThreadTaskRunner() {
1593 DCHECK(message_loop() == base::MessageLoop::current());
1594 if (!media_thread_
) {
1595 media_thread_
.reset(new base::Thread("Media"));
1596 media_thread_
->Start();
1598 #if defined(OS_ANDROID)
1599 renderer_demuxer_
= new RendererDemuxerAndroid();
1600 AddFilter(renderer_demuxer_
.get());
1603 return media_thread_
->message_loop_proxy();
1606 void RenderThreadImpl::SetFlingCurveParameters(
1607 const std::vector
<float>& new_touchpad
,
1608 const std::vector
<float>& new_touchscreen
) {
1609 webkit_platform_support_
->SetFlingCurveParameters(new_touchpad
,
1614 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1615 webkit_platform_support_
->sampleGamepads(*data
);
1618 void RenderThreadImpl::WidgetCreated() {
1622 void RenderThreadImpl::WidgetDestroyed() {
1626 void RenderThreadImpl::WidgetHidden() {
1627 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1628 hidden_widget_count_
++;
1630 if (widget_count_
&& hidden_widget_count_
== widget_count_
) {
1631 // TODO(reveman): Remove this when we have a better mechanism to prevent
1632 // total discardable memory used by all renderers from growing too large.
1633 base::internal::DiscardableMemoryEmulated::
1634 ReduceMemoryUsageUntilWithinLimit(
1635 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
);
1637 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1638 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1642 void RenderThreadImpl::WidgetRestored() {
1643 DCHECK_GT(hidden_widget_count_
, 0);
1644 hidden_widget_count_
--;
1646 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1650 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1653 } // namespace content