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/shared_memory.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/metrics/stats_table.h"
22 #include "base/path_service.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/string_tokenizer.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread_local.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/values.h"
30 #include "cc/base/switches.h"
31 #include "cc/resources/raster_worker_pool.h"
32 #include "content/child/appcache/appcache_dispatcher.h"
33 #include "content/child/appcache/appcache_frontend_impl.h"
34 #include "content/child/child_histogram_message_filter.h"
35 #include "content/child/db_message_filter.h"
36 #include "content/child/indexed_db/indexed_db_dispatcher.h"
37 #include "content/child/indexed_db/indexed_db_message_filter.h"
38 #include "content/child/npapi/npobject_util.h"
39 #include "content/child/plugin_messages.h"
40 #include "content/child/resource_dispatcher.h"
41 #include "content/child/runtime_features.h"
42 #include "content/child/thread_safe_sender.h"
43 #include "content/child/web_database_observer_impl.h"
44 #include "content/common/child_process_messages.h"
45 #include "content/common/content_constants_internal.h"
46 #include "content/common/database_messages.h"
47 #include "content/common/dom_storage/dom_storage_messages.h"
48 #include "content/common/gpu/client/context_provider_command_buffer.h"
49 #include "content/common/gpu/client/gpu_channel_host.h"
50 #include "content/common/gpu/client/gpu_memory_buffer_impl.h"
51 #include "content/common/gpu/gpu_messages.h"
52 #include "content/common/gpu/gpu_process_launch_causes.h"
53 #include "content/common/resource_messages.h"
54 #include "content/common/view_messages.h"
55 #include "content/public/common/content_constants.h"
56 #include "content/public/common/content_paths.h"
57 #include "content/public/common/content_switches.h"
58 #include "content/public/common/renderer_preferences.h"
59 #include "content/public/common/url_constants.h"
60 #include "content/public/renderer/content_renderer_client.h"
61 #include "content/public/renderer/render_process_observer.h"
62 #include "content/public/renderer/render_view_visitor.h"
63 #include "content/renderer/devtools/devtools_agent_filter.h"
64 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
65 #include "content/renderer/dom_storage/webstoragearea_impl.h"
66 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
67 #include "content/renderer/gamepad_shared_memory_reader.h"
68 #include "content/renderer/gpu/compositor_output_surface.h"
69 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
70 #include "content/renderer/input/input_event_filter.h"
71 #include "content/renderer/input/input_handler_manager.h"
72 #include "content/renderer/media/audio_input_message_filter.h"
73 #include "content/renderer/media/audio_message_filter.h"
74 #include "content/renderer/media/audio_renderer_mixer_manager.h"
75 #include "content/renderer/media/media_stream_center.h"
76 #include "content/renderer/media/media_stream_dependency_factory.h"
77 #include "content/renderer/media/midi_message_filter.h"
78 #include "content/renderer/media/peer_connection_tracker.h"
79 #include "content/renderer/media/video_capture_impl_manager.h"
80 #include "content/renderer/media/video_capture_message_filter.h"
81 #include "content/renderer/media/webrtc_identity_service.h"
82 #include "content/renderer/p2p/socket_dispatcher.h"
83 #include "content/renderer/render_process_impl.h"
84 #include "content/renderer/render_view_impl.h"
85 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
86 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
87 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
88 #include "grit/content_resources.h"
89 #include "ipc/ipc_channel_handle.h"
90 #include "ipc/ipc_forwarding_message_filter.h"
91 #include "ipc/ipc_platform_file.h"
92 #include "media/base/audio_hardware_config.h"
93 #include "media/base/media.h"
94 #include "media/filters/gpu_video_accelerator_factories.h"
95 #include "net/base/net_errors.h"
96 #include "net/base/net_util.h"
97 #include "third_party/WebKit/public/platform/WebString.h"
98 #include "third_party/WebKit/public/web/WebColorName.h"
99 #include "third_party/WebKit/public/web/WebDatabase.h"
100 #include "third_party/WebKit/public/web/WebDocument.h"
101 #include "third_party/WebKit/public/web/WebFrame.h"
102 #include "third_party/WebKit/public/web/WebImageCache.h"
103 #include "third_party/WebKit/public/web/WebKit.h"
104 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
105 #include "third_party/WebKit/public/web/WebPopupMenu.h"
106 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
107 #include "third_party/WebKit/public/web/WebScriptController.h"
108 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
109 #include "third_party/WebKit/public/web/WebView.h"
110 #include "third_party/skia/include/core/SkGraphics.h"
111 #include "ui/base/layout.h"
112 #include "ui/base/ui_base_switches.h"
113 #include "v8/include/v8.h"
114 #include "webkit/child/worker_task_runner.h"
115 #include "webkit/renderer/compositor_bindings/web_external_bitmap_impl.h"
122 #include "base/memory/scoped_handle.h"
123 #include "content/child/npapi/np_channel_base.h"
126 #if defined(OS_POSIX)
127 #include "ipc/ipc_channel_posix.h"
130 #if defined(OS_ANDROID)
131 #include <cpu-features.h>
132 #include "content/renderer/android/synchronous_compositor_factory.h"
133 #include "content/renderer/media/android/renderer_demuxer_android.h"
136 #if defined(ENABLE_PLUGINS)
137 #include "content/renderer/npapi/plugin_channel_host.h"
140 using base::ThreadRestrictions
;
141 using blink::WebDocument
;
142 using blink::WebFrame
;
143 using blink::WebNetworkStateNotifier
;
144 using blink::WebRuntimeFeatures
;
145 using blink::WebScriptController
;
146 using blink::WebSecurityPolicy
;
147 using blink::WebString
;
148 using blink::WebView
;
154 const int64 kInitialIdleHandlerDelayMs
= 1000;
155 const int64 kShortIdleHandlerDelayMs
= 1000;
156 const int64 kLongIdleHandlerDelayMs
= 30*1000;
157 const int kIdleCPUUsageThresholdInPercents
= 3;
158 const int kMinRasterThreads
= 1;
159 const int kMaxRasterThreads
= 64;
161 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
162 // incorrectly from the wrong thread.
163 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
164 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
166 class RenderViewZoomer
: public RenderViewVisitor
{
168 RenderViewZoomer(const std::string
& scheme
,
169 const std::string
& host
,
170 double zoom_level
) : scheme_(scheme
),
172 zoom_level_(zoom_level
) {
175 virtual bool Visit(RenderView
* render_view
) OVERRIDE
{
176 WebView
* webview
= render_view
->GetWebView();
177 WebDocument document
= webview
->mainFrame()->document();
179 // Don't set zoom level for full-page plugin since they don't use the same
181 if (document
.isPluginDocument())
183 GURL
url(document
.url());
184 // Empty scheme works as wildcard that matches any scheme,
185 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
186 (scheme_
.empty() || scheme_
== url
.scheme())) {
187 webview
->setZoomLevel(zoom_level_
);
193 const std::string scheme_
;
194 const std::string host_
;
195 const double zoom_level_
;
197 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
200 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
201 if (host
== "mail.google.com")
203 if (host
== "docs.google.com" || host
== "drive.google.com")
205 if (host
== "plus.google.com")
207 return std::string();
210 void* CreateHistogram(
211 const char *name
, int min
, int max
, size_t buckets
) {
214 std::string histogram_name
;
215 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
216 if (render_thread_impl
) { // Can be null in tests.
217 histogram_name
= render_thread_impl
->
218 histogram_customizer()->ConvertToCustomHistogramName(name
);
220 histogram_name
= std::string(name
);
222 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
223 histogram_name
, min
, max
, buckets
,
224 base::Histogram::kUmaTargetedHistogramFlag
);
228 void AddHistogramSample(void* hist
, int sample
) {
229 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
230 histogram
->Add(sample
);
233 scoped_ptr
<base::SharedMemory
> AllocateSharedMemoryFunction(size_t size
) {
234 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size
);
237 void EnableWebCoreLogChannels(const std::string
& channels
) {
238 if (channels
.empty())
240 base::StringTokenizer
t(channels
, ", ");
242 blink::enableLogChannel(t
.token().c_str());
247 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
248 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
249 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
250 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
253 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
255 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
256 const std::string
& host
, size_t view_count
) {
257 if (CommandLine::ForCurrentProcess()->HasSwitch(
258 switches::kDisableHistogramCustomizer
)) {
261 // Check if all RenderViews are displaying a page from the same host. If there
262 // is only one RenderView, the common host is this view's host. If there are
263 // many, check if this one shares the common host of the other
264 // RenderViews. It's ok to not detect some cases where the RenderViews share a
265 // common host. This information is only used for producing custom histograms.
268 else if (host
!= common_host_
)
269 SetCommonHost(std::string());
272 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
273 const char* histogram_name
) const {
274 std::string
name(histogram_name
);
275 if (!common_host_histogram_suffix_
.empty() &&
276 custom_histograms_
.find(name
) != custom_histograms_
.end())
277 name
+= common_host_histogram_suffix_
;
281 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
282 const std::string
& host
) {
283 if (host
!= common_host_
) {
285 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
286 v8::V8::SetCreateHistogramFunction(CreateHistogram
);
290 RenderThreadImpl
* RenderThreadImpl::current() {
291 return lazy_tls
.Pointer()->Get();
294 // When we run plugins in process, we actually run them on the render thread,
295 // which means that we need to make the render thread pump UI events.
296 RenderThreadImpl::RenderThreadImpl() {
300 RenderThreadImpl::RenderThreadImpl(const std::string
& channel_name
)
301 : ChildThread(channel_name
) {
305 void RenderThreadImpl::Init() {
306 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
308 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
309 base::PlatformThread::CurrentId(),
310 kTraceEventRendererMainThreadSortIndex
);
312 v8::V8::SetCounterFunction(base::StatsTable::FindLocation
);
313 v8::V8::SetCreateHistogramFunction(CreateHistogram
);
314 v8::V8::SetAddHistogramSampleFunction(AddHistogramSample
);
316 #if defined(OS_MACOSX) || defined(OS_ANDROID)
317 // On Mac and Android, the select popups are rendered by the browser.
318 blink::WebView::setUseExternalPopupMenus(true);
321 lazy_tls
.Pointer()->Set(this);
323 // Register this object as the main thread.
324 ChildProcess::current()->set_main_thread(this);
326 // In single process the single process is all there is.
327 suspend_webkit_shared_timer_
= true;
328 notify_webkit_of_modal_loop_
= true;
329 webkit_shared_timer_suspended_
= false;
331 hidden_widget_count_
= 0;
332 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
333 idle_notifications_to_skip_
= 0;
334 layout_test_mode_
= false;
335 shutdown_event_
= NULL
;
337 appcache_dispatcher_
.reset(
338 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
339 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
340 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
341 thread_safe_sender()));
342 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
344 media_stream_center_
= NULL
;
346 db_message_filter_
= new DBMessageFilter();
347 AddFilter(db_message_filter_
.get());
349 vc_manager_
.reset(new VideoCaptureImplManager());
350 AddFilter(vc_manager_
->video_capture_message_filter());
352 #if defined(ENABLE_WEBRTC)
353 peer_connection_tracker_
.reset(new PeerConnectionTracker());
354 AddObserver(peer_connection_tracker_
.get());
356 p2p_socket_dispatcher_
=
357 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
358 AddFilter(p2p_socket_dispatcher_
.get());
360 webrtc_identity_service_
.reset(new WebRTCIdentityService());
362 media_stream_factory_
.reset(new MediaStreamDependencyFactory(
363 p2p_socket_dispatcher_
.get()));
364 AddObserver(media_stream_factory_
.get());
365 #endif // defined(ENABLE_WEBRTC)
367 audio_input_message_filter_
=
368 new AudioInputMessageFilter(GetIOMessageLoopProxy());
369 AddFilter(audio_input_message_filter_
.get());
371 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
372 AddFilter(audio_message_filter_
.get());
374 midi_message_filter_
= new MIDIMessageFilter(GetIOMessageLoopProxy());
375 AddFilter(midi_message_filter_
.get());
377 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
379 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
381 GetContentClient()->renderer()->RenderThreadStarted();
383 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
384 if (command_line
.HasSwitch(switches::kEnableGpuBenchmarking
))
385 RegisterExtension(GpuBenchmarkingExtension::Get());
387 // Note that under Linux, the media library will normally already have
388 // been initialized by the Zygote before this instance became a Renderer.
389 base::FilePath media_path
;
390 PathService::Get(DIR_MEDIA_LIBS
, &media_path
);
391 if (!media_path
.empty())
392 media::InitializeMediaLibrary(media_path
);
394 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
395 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
397 std::vector
<base::DiscardableMemoryType
> supported_types
;
398 base::DiscardableMemory::GetSupportedTypes(&supported_types
);
399 DCHECK(!supported_types
.empty());
401 // The default preferred type is always the first one in list.
402 base::DiscardableMemoryType type
= supported_types
[0];
404 if (command_line
.HasSwitch(switches::kUseDiscardableMemory
)) {
405 std::string requested_type_name
= command_line
.GetSwitchValueASCII(
406 switches::kUseDiscardableMemory
);
407 base::DiscardableMemoryType requested_type
=
408 base::DiscardableMemory::GetNamedType(requested_type_name
);
409 if (std::find(supported_types
.begin(),
410 supported_types
.end(),
411 requested_type
) != supported_types
.end()) {
412 type
= requested_type
;
414 LOG(ERROR
) << "Requested discardable memory type is not supported.";
418 base::DiscardableMemory::SetPreferredType(type
);
420 // Allow discardable memory implementations to register memory pressure
422 base::DiscardableMemory::RegisterMemoryPressureListeners();
424 // AllocateGpuMemoryBuffer must be used exclusively on one thread but
425 // it doesn't have to be the same thread RenderThreadImpl is created on.
426 allocate_gpu_memory_buffer_thread_checker_
.DetachFromThread();
428 if (command_line
.HasSwitch(switches::kNumRasterThreads
)) {
429 int num_raster_threads
;
430 std::string string_value
=
431 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
432 if (base::StringToInt(string_value
, &num_raster_threads
) &&
433 num_raster_threads
>= kMinRasterThreads
&&
434 num_raster_threads
<= kMaxRasterThreads
) {
435 cc::RasterWorkerPool::SetNumRasterThreads(num_raster_threads
);
437 LOG(WARNING
) << "Failed to parse switch " <<
438 switches::kNumRasterThreads
<< ": " << string_value
;
442 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
445 RenderThreadImpl::~RenderThreadImpl() {
448 void RenderThreadImpl::Shutdown() {
450 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
452 ChildThread::Shutdown();
454 // Wait for all databases to be closed.
455 if (webkit_platform_support_
) {
456 webkit_platform_support_
->web_database_observer_impl()->
457 WaitForAllDatabasesToClose();
460 // Shutdown in reverse of the initialization order.
461 if (devtools_agent_message_filter_
.get()) {
462 RemoveFilter(devtools_agent_message_filter_
.get());
463 devtools_agent_message_filter_
= NULL
;
466 RemoveFilter(audio_input_message_filter_
.get());
467 audio_input_message_filter_
= NULL
;
469 RemoveFilter(audio_message_filter_
.get());
470 audio_message_filter_
= NULL
;
472 // |media_stream_factory_| produces users of |vc_manager_| so it must be
474 #if defined(ENABLE_WEBRTC)
475 media_stream_factory_
.reset();
477 RemoveFilter(vc_manager_
->video_capture_message_filter());
480 RemoveFilter(db_message_filter_
.get());
481 db_message_filter_
= NULL
;
483 // Shutdown the file thread if it's running.
485 file_thread_
->Stop();
487 if (compositor_output_surface_filter_
.get()) {
488 RemoveFilter(compositor_output_surface_filter_
.get());
489 compositor_output_surface_filter_
= NULL
;
492 compositor_thread_
.reset();
493 input_handler_manager_
.reset();
494 if (input_event_filter_
.get()) {
495 RemoveFilter(input_event_filter_
.get());
496 input_event_filter_
= NULL
;
499 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
500 // hold pointers to V8 objects (e.g., via pending requests).
501 main_thread_indexed_db_dispatcher_
.reset();
503 if (webkit_platform_support_
)
506 lazy_tls
.Pointer()->Set(NULL
);
510 // Clean up plugin channels before this thread goes away.
511 NPChannelBase::CleanupChannels();
514 // Leak shared contexts on other threads, as we can not get to the correct
515 // thread to destroy them.
516 if (offscreen_compositor_contexts_
.get())
517 offscreen_compositor_contexts_
->set_leak_on_destroy();
520 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
521 // Certain synchronous messages cannot always be processed synchronously by
522 // the browser, e.g., putting up UI and waiting for the user. This could cause
523 // a complete hang of Chrome if a windowed plug-in is trying to communicate
524 // with the renderer thread since the browser's UI thread could be stuck
525 // (within a Windows API call) trying to synchronously communicate with the
526 // plug-in. The remedy is to pump messages on this thread while the browser
527 // is processing this request. This creates an opportunity for re-entrancy
528 // into WebKit, so we need to take care to disable callbacks, timers, and
529 // pending network loads that could trigger such callbacks.
530 bool pumping_events
= false;
531 if (msg
->is_sync()) {
532 if (msg
->is_caller_pumping_messages()) {
533 pumping_events
= true;
537 bool suspend_webkit_shared_timer
= true; // default value
538 std::swap(suspend_webkit_shared_timer
, suspend_webkit_shared_timer_
);
540 bool notify_webkit_of_modal_loop
= true; // default value
541 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
543 #if defined(ENABLE_PLUGINS)
544 int render_view_id
= MSG_ROUTING_NONE
;
547 if (pumping_events
) {
548 if (suspend_webkit_shared_timer
)
549 webkit_platform_support_
->SuspendSharedTimer();
551 if (notify_webkit_of_modal_loop
)
552 WebView::willEnterModalLoop();
553 #if defined(ENABLE_PLUGINS)
554 RenderViewImpl
* render_view
=
555 RenderViewImpl::FromRoutingID(msg
->routing_id());
557 render_view_id
= msg
->routing_id();
558 PluginChannelHost::Broadcast(
559 new PluginMsg_SignalModalDialogEvent(render_view_id
));
564 bool rv
= ChildThread::Send(msg
);
566 if (pumping_events
) {
567 #if defined(ENABLE_PLUGINS)
568 if (render_view_id
!= MSG_ROUTING_NONE
) {
569 PluginChannelHost::Broadcast(
570 new PluginMsg_ResetModalDialogEvent(render_view_id
));
574 if (notify_webkit_of_modal_loop
)
575 WebView::didExitModalLoop();
577 if (suspend_webkit_shared_timer
)
578 webkit_platform_support_
->ResumeSharedTimer();
584 base::MessageLoop
* RenderThreadImpl::GetMessageLoop() {
585 return message_loop();
588 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
592 std::string
RenderThreadImpl::GetLocale() {
593 // The browser process should have passed the locale to the renderer via the
594 // --lang command line flag.
595 const CommandLine
& parsed_command_line
= *CommandLine::ForCurrentProcess();
596 const std::string
& lang
=
597 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
598 DCHECK(!lang
.empty());
602 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
603 return sync_message_filter();
606 scoped_refptr
<base::MessageLoopProxy
>
607 RenderThreadImpl::GetIOMessageLoopProxy() {
608 return ChildProcess::current()->io_message_loop_proxy();
611 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
612 ChildThread::AddRoute(routing_id
, listener
);
615 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
616 ChildThread::RemoveRoute(routing_id
);
618 int RenderThreadImpl::GenerateRoutingID() {
619 int routing_id
= MSG_ROUTING_NONE
;
620 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
624 void RenderThreadImpl::AddFilter(IPC::ChannelProxy::MessageFilter
* filter
) {
625 channel()->AddFilter(filter
);
628 void RenderThreadImpl::RemoveFilter(IPC::ChannelProxy::MessageFilter
* filter
) {
629 channel()->RemoveFilter(filter
);
632 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
633 observers_
.AddObserver(observer
);
636 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
637 observers_
.RemoveObserver(observer
);
640 void RenderThreadImpl::SetResourceDispatcherDelegate(
641 ResourceDispatcherDelegate
* delegate
) {
642 resource_dispatcher()->set_delegate(delegate
);
645 void RenderThreadImpl::EnsureWebKitInitialized() {
646 if (webkit_platform_support_
)
649 webkit_platform_support_
.reset(new RendererWebKitPlatformSupportImpl
);
650 blink::initialize(webkit_platform_support_
.get());
652 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
654 bool enable
= command_line
.HasSwitch(switches::kEnableThreadedCompositing
);
656 #if defined(OS_ANDROID)
657 if (SynchronousCompositorFactory
* factory
=
658 SynchronousCompositorFactory::GetInstance())
659 compositor_message_loop_proxy_
=
660 factory
->GetCompositorMessageLoop();
662 if (!compositor_message_loop_proxy_
.get()) {
663 compositor_thread_
.reset(new base::Thread("Compositor"));
664 compositor_thread_
->Start();
665 #if defined(OS_ANDROID)
666 compositor_thread_
->SetPriority(base::kThreadPriority_Display
);
668 compositor_message_loop_proxy_
=
669 compositor_thread_
->message_loop_proxy();
670 compositor_message_loop_proxy_
->PostTask(
672 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
676 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
677 #if defined(OS_ANDROID)
678 if (SynchronousCompositorFactory
* factory
=
679 SynchronousCompositorFactory::GetInstance()) {
680 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
683 if (!input_handler_manager_client
) {
684 input_event_filter_
=
685 new InputEventFilter(this, compositor_message_loop_proxy_
);
686 AddFilter(input_event_filter_
.get());
687 input_handler_manager_client
= input_event_filter_
.get();
689 input_handler_manager_
.reset(
690 new InputHandlerManager(compositor_message_loop_proxy_
,
691 input_handler_manager_client
));
694 scoped_refptr
<base::MessageLoopProxy
> output_surface_loop
;
696 output_surface_loop
= compositor_message_loop_proxy_
;
698 output_surface_loop
= base::MessageLoopProxy::current();
700 compositor_output_surface_filter_
=
701 CompositorOutputSurface::CreateFilter(output_surface_loop
.get());
702 AddFilter(compositor_output_surface_filter_
.get());
704 WebScriptController::enableV8SingleThreadMode();
706 RenderThreadImpl::RegisterSchemes();
708 EnableWebCoreLogChannels(
709 command_line
.GetSwitchValueASCII(switches::kWebCoreLogChannels
));
711 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
713 if (!media::IsMediaLibraryInitialized()) {
714 WebRuntimeFeatures::enableMediaPlayer(false);
715 WebRuntimeFeatures::enableWebAudio(false);
718 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
720 devtools_agent_message_filter_
= new DevToolsAgentFilter();
721 AddFilter(devtools_agent_message_filter_
.get());
723 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
724 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
726 webkit::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction
);
728 // Limit use of the scaled image cache to when deferred image decoding
730 // TODO(reveman): Allow use of this cache on Android once
731 // SkDiscardablePixelRef is used for decoded images. crbug.com/330041
732 bool use_skia_scaled_image_cache
= false;
733 #if !defined(OS_ANDROID)
734 use_skia_scaled_image_cache
=
735 command_line
.HasSwitch(switches::kEnableDeferredImageDecoding
) ||
736 cc::switches::IsImplSidePaintingEnabled();
738 if (!use_skia_scaled_image_cache
)
739 SkGraphics::SetImageCacheByteLimit(0u);
742 void RenderThreadImpl::RegisterSchemes() {
743 // swappedout: pages should not be accessible, and should also
744 // be treated as empty documents that can commit synchronously.
745 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
746 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
747 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
750 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
751 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
754 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
755 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
758 scoped_ptr
<base::SharedMemory
>
759 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
760 if (size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
761 return scoped_ptr
<base::SharedMemory
>();
763 base::SharedMemoryHandle handle
;
765 IPC::Message
* message
=
766 new ChildProcessHostMsg_SyncAllocateSharedMemory(size
, &handle
);
768 // Allow calling this from the compositor thread.
769 if (base::MessageLoop::current() == message_loop())
770 success
= ChildThread::Send(message
);
772 success
= sync_message_filter()->Send(message
);
775 return scoped_ptr
<base::SharedMemory
>();
777 if (!base::SharedMemory::IsHandleValid(handle
))
778 return scoped_ptr
<base::SharedMemory
>();
780 return scoped_ptr
<base::SharedMemory
>(new base::SharedMemory(handle
, false));
783 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
784 WebScriptController::registerExtension(extension
);
787 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
788 idle_notification_delay_in_ms_
= initial_delay_ms
;
790 idle_timer_
.Start(FROM_HERE
,
791 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
792 this, &RenderThreadImpl::IdleHandler
);
795 void RenderThreadImpl::IdleHandler() {
796 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
797 GetContentClient()->renderer()->
798 RunIdleHandlerWhenWidgetsHidden();
799 if (run_in_foreground_tab
) {
800 IdleHandlerInForegroundTab();
804 base::allocator::ReleaseFreeMemory();
806 // Continue the idle timer if the webkit shared timer is not suspended or
807 // something is left to do.
808 bool continue_timer
= !webkit_shared_timer_suspended_
;
810 if (!v8::V8::IdleNotification()) {
811 continue_timer
= true;
814 // Schedule next invocation.
815 // Dampen the delay using the algorithm (if delay is in seconds):
816 // delay = delay + 1 / (delay + 2)
817 // Using floor(delay) has a dampening effect such as:
818 // 1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
819 // If the delay is in milliseconds, the above formula is equivalent to:
820 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
821 // which is equivalent to
822 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
823 // Note that idle_notification_delay_in_ms_ would be reset to
824 // kInitialIdleHandlerDelayMs in RenderThreadImpl::WidgetHidden.
825 if (continue_timer
) {
826 ScheduleIdleHandler(idle_notification_delay_in_ms_
+
827 1000000 / (idle_notification_delay_in_ms_
+ 2000));
833 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
836 void RenderThreadImpl::IdleHandlerInForegroundTab() {
837 // Increase the delay in the same way as in IdleHandler,
838 // but make it periodic by reseting it once it is too big.
839 int64 new_delay_ms
= idle_notification_delay_in_ms_
+
840 1000000 / (idle_notification_delay_in_ms_
+ 2000);
841 if (new_delay_ms
>= kLongIdleHandlerDelayMs
)
842 new_delay_ms
= kShortIdleHandlerDelayMs
;
844 if (idle_notifications_to_skip_
> 0) {
845 idle_notifications_to_skip_
--;
848 Send(new ViewHostMsg_GetCPUUsage(&cpu_usage
));
849 // Idle notification hint roughly specifies the expected duration of the
850 // idle pause. We set it proportional to the idle timer delay.
851 int idle_hint
= static_cast<int>(new_delay_ms
/ 10);
852 if (cpu_usage
< kIdleCPUUsageThresholdInPercents
) {
853 base::allocator::ReleaseFreeMemory();
854 if (v8::V8::IdleNotification(idle_hint
)) {
855 // V8 finished collecting garbage.
856 new_delay_ms
= kLongIdleHandlerDelayMs
;
860 ScheduleIdleHandler(new_delay_ms
);
863 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
864 return idle_notification_delay_in_ms_
;
867 void RenderThreadImpl::SetIdleNotificationDelayInMs(
868 int64 idle_notification_delay_in_ms
) {
869 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
872 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
873 child_histogram_message_filter()->SendHistograms(sequence_number
);
876 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
877 return webkit_glue::WorkerTaskRunner::Instance()->PostTaskToAllThreads(
881 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
883 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
887 void RenderThreadImpl::PostponeIdleNotification() {
888 idle_notifications_to_skip_
= 2;
891 scoped_refptr
<RendererGpuVideoAcceleratorFactories
>
892 RenderThreadImpl::GetGpuFactories() {
893 DCHECK(IsMainThread());
895 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
896 const CommandLine
* cmd_line
= CommandLine::ForCurrentProcess();
897 scoped_refptr
<RendererGpuVideoAcceleratorFactories
> gpu_factories
;
898 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
899 if (!gpu_va_context_provider_
||
900 gpu_va_context_provider_
->DestroyedOnMainThread()) {
901 if (!gpu_channel_host
) {
902 gpu_channel_host
= EstablishGpuChannelSync(
903 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
905 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
907 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
908 gpu_channel_host
.get(),
909 blink::WebGraphicsContext3D::Attributes(),
910 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
911 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits())),
912 "GPU-VideoAccelerator-Offscreen");
915 if (gpu_channel_host
) {
916 gpu_factories
= new RendererGpuVideoAcceleratorFactories(
917 gpu_channel_host
.get(), gpu_va_context_provider_
);
919 return gpu_factories
;
922 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
923 RenderThreadImpl::CreateOffscreenContext3d() {
924 blink::WebGraphicsContext3D::Attributes attributes
;
925 attributes
.shareResources
= true;
926 attributes
.depth
= false;
927 attributes
.stencil
= false;
928 attributes
.antialias
= false;
929 attributes
.noAutomaticFlushes
= true;
931 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
932 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
933 return make_scoped_ptr(
934 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
935 gpu_channel_host
.get(),
937 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
938 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits()));
941 scoped_refptr
<cc::ContextProvider
>
942 RenderThreadImpl::OffscreenCompositorContextProvider() {
943 DCHECK(IsMainThread());
945 #if defined(OS_ANDROID)
946 if (SynchronousCompositorFactory
* factory
=
947 SynchronousCompositorFactory::GetInstance()) {
948 if (compositor_message_loop_proxy_
)
949 return factory
->GetOffscreenContextProviderForCompositorThread();
950 return factory
->GetOffscreenContextProviderForMainThread();
954 if (!offscreen_compositor_contexts_
.get() ||
955 offscreen_compositor_contexts_
->DestroyedOnMainThread()) {
956 offscreen_compositor_contexts_
= ContextProviderCommandBuffer::Create(
957 CreateOffscreenContext3d(),
958 "Compositor-Offscreen");
960 return offscreen_compositor_contexts_
;
963 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
964 RenderThreadImpl::SharedMainThreadContextProvider() {
965 DCHECK(IsMainThread());
966 #if defined(OS_ANDROID)
967 if (SynchronousCompositorFactory
* factory
=
968 SynchronousCompositorFactory::GetInstance())
969 return factory
->GetOffscreenContextProviderForMainThread();
972 if (!shared_main_thread_contexts_
||
973 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
974 if (compositor_message_loop_proxy_
) {
975 // In threaded compositing mode, we have to create a new ContextProvider
976 // to bind to the main thread since the compositor's is bound to the
977 // compositor thread.
978 shared_main_thread_contexts_
=
979 ContextProviderCommandBuffer::Create(CreateOffscreenContext3d(),
980 "Offscreen-MainThread");
982 // In single threaded mode, we can use the same context provider.
983 shared_main_thread_contexts_
=
984 static_cast<ContextProviderCommandBuffer
*>(
985 OffscreenCompositorContextProvider().get());
988 if (shared_main_thread_contexts_
&&
989 !shared_main_thread_contexts_
->BindToCurrentThread())
990 shared_main_thread_contexts_
= NULL
;
991 return shared_main_thread_contexts_
;
994 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
995 if (!audio_renderer_mixer_manager_
) {
996 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
997 GetAudioHardwareConfig()));
1000 return audio_renderer_mixer_manager_
.get();
1003 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1004 if (!audio_hardware_config_
) {
1005 media::AudioParameters input_params
;
1006 media::AudioParameters output_params
;
1007 Send(new ViewHostMsg_GetAudioHardwareConfig(
1008 &input_params
, &output_params
));
1010 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1011 input_params
, output_params
));
1012 audio_message_filter_
->SetAudioHardwareConfig(audio_hardware_config_
.get());
1015 return audio_hardware_config_
.get();
1019 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1020 const base::string16
& str
) {
1021 Send(new ViewHostMsg_PreCacheFontCharacters(log_font
, str
));
1024 void RenderThreadImpl::PreCacheFont(const LOGFONT
& log_font
) {
1025 Send(new ChildProcessHostMsg_PreCacheFont(log_font
));
1028 void RenderThreadImpl::ReleaseCachedFonts() {
1029 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1034 bool RenderThreadImpl::IsMainThread() {
1038 base::MessageLoop
* RenderThreadImpl::GetMainLoop() {
1039 return message_loop();
1042 scoped_refptr
<base::MessageLoopProxy
> RenderThreadImpl::GetIOLoopProxy() {
1043 return io_message_loop_proxy_
;
1046 base::WaitableEvent
* RenderThreadImpl::GetShutDownEvent() {
1047 return shutdown_event_
;
1050 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1052 return scoped_ptr
<base::SharedMemory
>(
1053 HostAllocateSharedMemoryBuffer(size
));
1056 int32
RenderThreadImpl::CreateViewCommandBuffer(
1057 int32 surface_id
, const GPUCreateCommandBufferConfig
& init_params
) {
1059 "RenderThreadImpl::CreateViewCommandBuffer",
1063 int32 route_id
= MSG_ROUTING_NONE
;
1064 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1069 // Allow calling this from the compositor thread.
1070 thread_safe_sender()->Send(message
);
1075 void RenderThreadImpl::CreateImage(
1076 gfx::PluginWindowHandle window
,
1078 const CreateImageCallback
& callback
) {
1082 void RenderThreadImpl::DeleteImage(int32 image_id
, int32 sync_point
) {
1086 scoped_ptr
<gfx::GpuMemoryBuffer
> RenderThreadImpl::AllocateGpuMemoryBuffer(
1089 unsigned internalformat
) {
1090 DCHECK(allocate_gpu_memory_buffer_thread_checker_
.CalledOnValidThread());
1092 if (!GpuMemoryBufferImpl::IsFormatValid(internalformat
))
1093 return scoped_ptr
<gfx::GpuMemoryBuffer
>();
1095 gfx::GpuMemoryBufferHandle handle
;
1097 IPC::Message
* message
=
1098 new ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer(width
,
1103 // Allow calling this from the compositor thread.
1104 if (base::MessageLoop::current() == message_loop())
1105 success
= ChildThread::Send(message
);
1107 success
= sync_message_filter()->Send(message
);
1110 return scoped_ptr
<gfx::GpuMemoryBuffer
>();
1112 return GpuMemoryBufferImpl::Create(
1114 gfx::Size(width
, height
),
1115 internalformat
).PassAs
<gfx::GpuMemoryBuffer
>();
1118 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1119 suspend_webkit_shared_timer_
= false;
1122 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1123 notify_webkit_of_modal_loop_
= false;
1126 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1127 const std::string
& host
,
1128 double zoom_level
) {
1129 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1130 RenderView::ForEach(&zoomer
);
1133 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1134 ObserverListBase
<RenderProcessObserver
>::Iterator
it(observers_
);
1135 RenderProcessObserver
* observer
;
1136 while ((observer
= it
.GetNext()) != NULL
) {
1137 if (observer
->OnControlMessageReceived(msg
))
1141 // Some messages are handled by delegates.
1142 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1143 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1144 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1148 bool handled
= true;
1149 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1150 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1151 OnSetZoomLevelForCurrentURL
)
1152 // TODO(port): removed from render_messages_internal.h;
1153 // is there a new non-windows message I should add here?
1154 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1155 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1156 IPC_MESSAGE_HANDLER(ViewMsg_NetworkStateChanged
, OnNetworkStateChanged
)
1157 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData
, OnTempCrashWithData
)
1158 #if defined(OS_ANDROID)
1159 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1160 OnSetWebKitSharedTimersSuspended
)
1162 #if defined(OS_MACOSX)
1163 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1165 IPC_MESSAGE_UNHANDLED(handled
= false)
1166 IPC_END_MESSAGE_MAP()
1170 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1171 EnsureWebKitInitialized();
1172 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1173 RenderViewImpl::Create(
1174 params
.opener_route_id
,
1175 params
.renderer_preferences
,
1176 params
.web_preferences
,
1178 params
.main_frame_routing_id
,
1180 params
.session_storage_namespace_id
,
1185 params
.next_page_id
,
1187 params
.accessibility_mode
,
1188 params
.allow_partial_swap
);
1191 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1192 CauseForGpuLaunch cause_for_gpu_launch
) {
1193 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1195 if (gpu_channel_
.get()) {
1196 // Do nothing if we already have a GPU channel or are already
1197 // establishing one.
1198 if (!gpu_channel_
->IsLost())
1199 return gpu_channel_
.get();
1201 // Recreate the channel if it has been lost.
1202 gpu_channel_
= NULL
;
1205 // Ask the browser for the channel name.
1207 IPC::ChannelHandle channel_handle
;
1208 gpu::GPUInfo gpu_info
;
1209 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1213 #if defined(OS_POSIX)
1214 channel_handle
.socket
.fd
== -1 ||
1216 channel_handle
.name
.empty()) {
1217 // Otherwise cancel the connection.
1221 GetContentClient()->SetGpuInfo(gpu_info
);
1223 // Cache some variables that are needed on the compositor thread for our
1224 // implementation of GpuChannelHostFactory.
1225 io_message_loop_proxy_
= ChildProcess::current()->io_message_loop_proxy();
1226 shutdown_event_
= ChildProcess::current()->GetShutDownEvent();
1228 gpu_channel_
= GpuChannelHost::Create(this, gpu_info
, channel_handle
);
1229 return gpu_channel_
.get();
1232 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1233 blink::WebMediaStreamCenterClient
* client
) {
1234 #if defined(OS_ANDROID)
1235 if (CommandLine::ForCurrentProcess()->HasSwitch(
1236 switches::kDisableWebRTC
))
1240 #if defined(ENABLE_WEBRTC)
1241 if (!media_stream_center_
) {
1242 media_stream_center_
= GetContentClient()->renderer()
1243 ->OverrideCreateWebMediaStreamCenter(client
);
1244 if (!media_stream_center_
) {
1245 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1246 new MediaStreamCenter(client
, GetMediaStreamDependencyFactory()));
1247 AddObserver(media_stream_center
.get());
1248 media_stream_center_
= media_stream_center
.release();
1252 return media_stream_center_
;
1255 MediaStreamDependencyFactory
*
1256 RenderThreadImpl::GetMediaStreamDependencyFactory() {
1257 return media_stream_factory_
.get();
1260 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1261 if (!gpu_channel_
.get())
1264 if (gpu_channel_
->IsLost())
1267 return gpu_channel_
.get();
1270 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1271 EnsureWebKitInitialized();
1272 // The call below will cause a GetPlugins call with refresh=true, but at this
1273 // point we already know that the browser has refreshed its list, so disable
1274 // refresh temporarily to prevent each renderer process causing the list to be
1276 webkit_platform_support_
->set_plugin_refresh_allowed(false);
1277 blink::resetPluginCache(reload_pages
);
1278 webkit_platform_support_
->set_plugin_refresh_allowed(true);
1280 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1283 void RenderThreadImpl::OnNetworkStateChanged(bool online
) {
1284 EnsureWebKitInitialized();
1285 WebNetworkStateNotifier::setOnLine(online
);
1288 void RenderThreadImpl::OnTempCrashWithData(const GURL
& data
) {
1289 GetContentClient()->SetActiveURL(data
);
1293 #if defined(OS_ANDROID)
1294 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1295 if (suspend_webkit_shared_timer_
) {
1296 EnsureWebKitInitialized();
1298 webkit_platform_support_
->SuspendSharedTimer();
1300 webkit_platform_support_
->ResumeSharedTimer();
1302 webkit_shared_timer_suspended_
= suspend
;
1307 #if defined(OS_MACOSX)
1308 void RenderThreadImpl::OnUpdateScrollbarTheme(
1309 float initial_button_delay
,
1310 float autoscroll_button_delay
,
1311 bool jump_on_track_click
,
1312 blink::ScrollerStyle preferred_scroller_style
,
1314 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay
,
1315 autoscroll_button_delay
,
1316 jump_on_track_click
,
1317 preferred_scroller_style
,
1322 void RenderThreadImpl::OnMemoryPressure(
1323 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1324 base::allocator::ReleaseFreeMemory();
1326 if (memory_pressure_level
==
1327 base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL
) {
1328 // Trigger full v8 garbage collection on critical memory notification.
1329 v8::V8::LowMemoryNotification();
1330 // Clear the image cache.
1331 blink::WebImageCache::clear();
1332 // Purge Skia font cache, by setting it to 0 and then again to the previous
1334 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1335 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1337 // Otherwise trigger a couple of v8 GCs using IdleNotification.
1338 if (!v8::V8::IdleNotification())
1339 v8::V8::IdleNotification();
1343 scoped_refptr
<base::MessageLoopProxy
>
1344 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1345 DCHECK(message_loop() == base::MessageLoop::current());
1346 if (!file_thread_
) {
1347 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1348 file_thread_
->Start();
1350 return file_thread_
->message_loop_proxy();
1353 scoped_refptr
<base::MessageLoopProxy
>
1354 RenderThreadImpl::GetMediaThreadMessageLoopProxy() {
1355 DCHECK(message_loop() == base::MessageLoop::current());
1356 if (!media_thread_
) {
1357 media_thread_
.reset(new base::Thread("Media"));
1358 media_thread_
->Start();
1360 #if defined(OS_ANDROID)
1361 renderer_demuxer_
= new RendererDemuxerAndroid();
1362 AddFilter(renderer_demuxer_
.get());
1365 return media_thread_
->message_loop_proxy();
1368 void RenderThreadImpl::SetFlingCurveParameters(
1369 const std::vector
<float>& new_touchpad
,
1370 const std::vector
<float>& new_touchscreen
) {
1371 webkit_platform_support_
->SetFlingCurveParameters(new_touchpad
,
1376 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1377 if (!gamepad_shared_memory_reader_
)
1378 gamepad_shared_memory_reader_
.reset(new GamepadSharedMemoryReader
);
1379 gamepad_shared_memory_reader_
->SampleGamepads(*data
);
1382 void RenderThreadImpl::WidgetCreated() {
1386 void RenderThreadImpl::WidgetDestroyed() {
1390 void RenderThreadImpl::WidgetHidden() {
1391 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1392 hidden_widget_count_
++;
1394 if (widget_count_
&& hidden_widget_count_
== widget_count_
) {
1395 #if !defined(SYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE)
1396 // TODO(vollick): Remove this this heavy-handed approach once we're polling
1397 // the real system memory pressure.
1398 base::MemoryPressureListener::NotifyMemoryPressure(
1399 base::MemoryPressureListener::MEMORY_PRESSURE_MODERATE
);
1401 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1402 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1406 void RenderThreadImpl::WidgetRestored() {
1407 DCHECK_GT(hidden_widget_count_
, 0);
1408 hidden_widget_count_
--;
1410 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1414 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1417 } // namespace content