[Android] Fix buildbot scripts for components_browsertests.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blob61fd8409dfa26dbbb2a2e52266667ea9a2d9180f
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"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <vector>
12 #include "base/allocator/allocator_extension.h"
13 #include "base/command_line.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/memory/discardable_memory_allocator.h"
17 #include "base/memory/shared_memory.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/path_service.h"
21 #include "base/single_thread_task_runner.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_tokenizer.h"
25 #include "base/strings/sys_string_conversions.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/simple_thread.h"
28 #include "base/threading/thread_local.h"
29 #include "base/threading/thread_restrictions.h"
30 #include "base/trace_event/trace_event.h"
31 #include "base/values.h"
32 #include "cc/base/switches.h"
33 #include "cc/blink/web_external_bitmap_impl.h"
34 #include "cc/blink/web_layer_impl.h"
35 #include "cc/resources/tile_task_worker_pool.h"
36 #include "components/scheduler/renderer/renderer_scheduler.h"
37 #include "content/child/appcache/appcache_dispatcher.h"
38 #include "content/child/appcache/appcache_frontend_impl.h"
39 #include "content/child/child_discardable_shared_memory_manager.h"
40 #include "content/child/child_gpu_memory_buffer_manager.h"
41 #include "content/child/child_histogram_message_filter.h"
42 #include "content/child/child_resource_message_filter.h"
43 #include "content/child/child_shared_bitmap_manager.h"
44 #include "content/child/content_child_helpers.h"
45 #include "content/child/db_message_filter.h"
46 #include "content/child/indexed_db/indexed_db_dispatcher.h"
47 #include "content/child/indexed_db/indexed_db_message_filter.h"
48 #include "content/child/npapi/npobject_util.h"
49 #include "content/child/plugin_messages.h"
50 #include "content/child/resource_dispatcher.h"
51 #include "content/child/resource_scheduling_filter.h"
52 #include "content/child/runtime_features.h"
53 #include "content/child/thread_safe_sender.h"
54 #include "content/child/web_database_observer_impl.h"
55 #include "content/child/worker_task_runner.h"
56 #include "content/common/child_process_messages.h"
57 #include "content/common/content_constants_internal.h"
58 #include "content/common/database_messages.h"
59 #include "content/common/dom_storage/dom_storage_messages.h"
60 #include "content/common/frame_messages.h"
61 #include "content/common/gpu/client/context_provider_command_buffer.h"
62 #include "content/common/gpu/client/gpu_channel_host.h"
63 #include "content/common/gpu/gpu_messages.h"
64 #include "content/common/gpu/gpu_process_launch_causes.h"
65 #include "content/common/render_frame_setup.mojom.h"
66 #include "content/common/resource_messages.h"
67 #include "content/common/view_messages.h"
68 #include "content/common/worker_messages.h"
69 #include "content/public/common/content_constants.h"
70 #include "content/public/common/content_paths.h"
71 #include "content/public/common/content_switches.h"
72 #include "content/public/common/mojo_channel_switches.h"
73 #include "content/public/common/renderer_preferences.h"
74 #include "content/public/common/url_constants.h"
75 #include "content/public/renderer/content_renderer_client.h"
76 #include "content/public/renderer/render_process_observer.h"
77 #include "content/public/renderer/render_view_visitor.h"
78 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
79 #include "content/renderer/cache_storage/cache_storage_dispatcher.h"
80 #include "content/renderer/cache_storage/cache_storage_message_filter.h"
81 #include "content/renderer/devtools/devtools_agent_filter.h"
82 #include "content/renderer/devtools/v8_sampling_profiler.h"
83 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
84 #include "content/renderer/dom_storage/webstoragearea_impl.h"
85 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
86 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
87 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
88 #include "content/renderer/gpu/compositor_output_surface.h"
89 #include "content/renderer/input/input_event_filter.h"
90 #include "content/renderer/input/input_handler_manager.h"
91 #include "content/renderer/input/main_thread_input_event_filter.h"
92 #include "content/renderer/media/aec_dump_message_filter.h"
93 #include "content/renderer/media/audio_input_message_filter.h"
94 #include "content/renderer/media/audio_message_filter.h"
95 #include "content/renderer/media/audio_renderer_mixer_manager.h"
96 #include "content/renderer/media/media_stream_center.h"
97 #include "content/renderer/media/midi_message_filter.h"
98 #include "content/renderer/media/render_media_client.h"
99 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
100 #include "content/renderer/media/video_capture_impl_manager.h"
101 #include "content/renderer/media/video_capture_message_filter.h"
102 #include "content/renderer/net_info_helper.h"
103 #include "content/renderer/p2p/socket_dispatcher.h"
104 #include "content/renderer/render_frame_proxy.h"
105 #include "content/renderer/render_process_impl.h"
106 #include "content/renderer/render_view_impl.h"
107 #include "content/renderer/renderer_blink_platform_impl.h"
108 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
109 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
110 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
111 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
112 #include "gin/public/debug.h"
113 #include "gpu/GLES2/gl2extchromium.h"
114 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
115 #include "ipc/ipc_channel_handle.h"
116 #include "ipc/ipc_platform_file.h"
117 #include "ipc/mojo/ipc_channel_mojo.h"
118 #include "media/base/audio_hardware_config.h"
119 #include "media/base/media.h"
120 #include "media/renderers/gpu_video_accelerator_factories.h"
121 #include "mojo/common/common_type_converters.h"
122 #include "net/base/net_errors.h"
123 #include "net/base/net_util.h"
124 #include "skia/ext/event_tracer_impl.h"
125 #include "third_party/WebKit/public/platform/WebString.h"
126 #include "third_party/WebKit/public/platform/WebThread.h"
127 #include "third_party/WebKit/public/web/WebCache.h"
128 #include "third_party/WebKit/public/web/WebColorName.h"
129 #include "third_party/WebKit/public/web/WebDatabase.h"
130 #include "third_party/WebKit/public/web/WebDocument.h"
131 #include "third_party/WebKit/public/web/WebFrame.h"
132 #include "third_party/WebKit/public/web/WebImageCache.h"
133 #include "third_party/WebKit/public/web/WebKit.h"
134 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
135 #include "third_party/WebKit/public/web/WebPopupMenu.h"
136 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
137 #include "third_party/WebKit/public/web/WebScriptController.h"
138 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
139 #include "third_party/WebKit/public/web/WebView.h"
140 #include "third_party/skia/include/core/SkGraphics.h"
141 #include "ui/base/layout.h"
142 #include "ui/base/ui_base_switches.h"
143 #include "v8/include/v8.h"
145 #if defined(OS_ANDROID)
146 #include <cpu-features.h>
147 #include "content/renderer/android/synchronous_compositor_factory.h"
148 #include "content/renderer/media/android/renderer_demuxer_android.h"
149 #endif
151 #if defined(OS_MACOSX)
152 #include "base/mac/mac_util.h"
153 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
154 #endif
156 #if defined(OS_POSIX)
157 #include "ipc/ipc_channel_posix.h"
158 #endif
160 #if defined(OS_WIN)
161 #include <windows.h>
162 #include <objbase.h>
163 #else
164 // TODO(port)
165 #include "content/child/npapi/np_channel_base.h"
166 #endif
168 #if defined(ENABLE_PLUGINS)
169 #include "content/renderer/npapi/plugin_channel_host.h"
170 #endif
172 #if defined(ENABLE_WEBRTC)
173 #include "content/renderer/media/peer_connection_tracker.h"
174 #include "content/renderer/media/rtc_peer_connection_handler.h"
175 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
176 #include "content/renderer/media/webrtc_identity_service.h"
177 #endif
179 #ifdef ENABLE_VTUNE_JIT_INTERFACE
180 #include "v8/src/third_party/vtune/v8-vtune.h"
181 #endif
183 using base::ThreadRestrictions;
184 using blink::WebDocument;
185 using blink::WebFrame;
186 using blink::WebNetworkStateNotifier;
187 using blink::WebRuntimeFeatures;
188 using blink::WebScriptController;
189 using blink::WebSecurityPolicy;
190 using blink::WebString;
191 using blink::WebView;
193 namespace content {
195 namespace {
197 const int64 kInitialIdleHandlerDelayMs = 1000;
198 const int64 kLongIdleHandlerDelayMs = 30*1000;
200 #if defined(OS_ANDROID)
201 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
202 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
203 // induced work takes but a fraction (~1/4) of the overall frame budget.
204 const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
205 #else
206 const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
207 #endif
208 const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
210 // Maximum allocation size allowed for image scaling filters that
211 // require pre-scaling. Skia will fallback to a filter that doesn't
212 // require pre-scaling if the default filter would require an
213 // allocation that exceeds this limit.
214 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
216 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
217 // incorrectly from the wrong thread.
218 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
219 lazy_tls = LAZY_INSTANCE_INITIALIZER;
221 class RenderViewZoomer : public RenderViewVisitor {
222 public:
223 RenderViewZoomer(const std::string& scheme,
224 const std::string& host,
225 double zoom_level) : scheme_(scheme),
226 host_(host),
227 zoom_level_(zoom_level) {
230 bool Visit(RenderView* render_view) override {
231 WebView* webview = render_view->GetWebView();
232 // Remote frames don't host documents.
233 // TODO(wjmaclean) Although it seems likely that a frame without a
234 // document can safely early-out here, we should confirm this is truly
235 // the case. https://crbug.com/477007
236 if (webview->mainFrame()->isWebRemoteFrame())
237 return true;
239 WebDocument document = webview->mainFrame()->document();
241 // Don't set zoom level for full-page plugin since they don't use the same
242 // zoom settings.
243 if (document.isPluginDocument())
244 return true;
245 GURL url(document.url());
246 // Empty scheme works as wildcard that matches any scheme,
247 if ((net::GetHostOrSpecFromURL(url) == host_) &&
248 (scheme_.empty() || scheme_ == url.scheme()) &&
249 !static_cast<RenderViewImpl*>(render_view)
250 ->uses_temporary_zoom_level()) {
251 webview->hidePopups();
252 webview->setZoomLevel(zoom_level_);
254 return true;
257 private:
258 const std::string scheme_;
259 const std::string host_;
260 const double zoom_level_;
262 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
265 class CompositorRasterThread : public base::SimpleThread {
266 public:
267 CompositorRasterThread(cc::TaskGraphRunner* task_graph_runner,
268 const std::string& name_prefix)
269 : base::SimpleThread(name_prefix),
270 task_graph_runner_(task_graph_runner) {}
272 // Overridden from base::SimpleThread:
273 void Run() override { task_graph_runner_->Run(); }
275 private:
276 cc::TaskGraphRunner* task_graph_runner_;
278 DISALLOW_COPY_AND_ASSIGN(CompositorRasterThread);
281 std::string HostToCustomHistogramSuffix(const std::string& host) {
282 if (host == "mail.google.com")
283 return ".gmail";
284 if (host == "docs.google.com" || host == "drive.google.com")
285 return ".docs";
286 if (host == "plus.google.com")
287 return ".plus";
288 return std::string();
291 void* CreateHistogram(
292 const char *name, int min, int max, size_t buckets) {
293 if (min <= 0)
294 min = 1;
295 std::string histogram_name;
296 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
297 if (render_thread_impl) { // Can be null in tests.
298 histogram_name = render_thread_impl->
299 histogram_customizer()->ConvertToCustomHistogramName(name);
300 } else {
301 histogram_name = std::string(name);
303 base::HistogramBase* histogram = base::Histogram::FactoryGet(
304 histogram_name, min, max, buckets,
305 base::Histogram::kUmaTargetedHistogramFlag);
306 return histogram;
309 void AddHistogramSample(void* hist, int sample) {
310 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
311 histogram->Add(sample);
314 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
315 const gfx::Size& size) {
316 return ChildThreadImpl::current()->shared_bitmap_manager()->
317 AllocateSharedBitmap(size);
320 void EnableBlinkPlatformLogChannels(const std::string& channels) {
321 if (channels.empty())
322 return;
323 base::StringTokenizer t(channels, ", ");
324 while (t.GetNext())
325 blink::enableLogChannel(t.token().c_str());
328 void NotifyTimezoneChangeOnThisThread() {
329 v8::Isolate* isolate = v8::Isolate::GetCurrent();
330 if (!isolate)
331 return;
332 v8::Date::DateTimeConfigurationChangeNotification(isolate);
335 void LowMemoryNotificationOnThisThread() {
336 v8::Isolate* isolate = v8::Isolate::GetCurrent();
337 if (!isolate)
338 return;
339 isolate->LowMemoryNotification();
342 class RenderFrameSetupImpl : public mojo::InterfaceImpl<RenderFrameSetup> {
343 public:
344 RenderFrameSetupImpl()
345 : routing_id_highmark_(-1) {
348 void ExchangeServiceProviders(
349 int32_t frame_routing_id,
350 mojo::InterfaceRequest<mojo::ServiceProvider> services,
351 mojo::ServiceProviderPtr exposed_services)
352 override {
353 // TODO(morrita): This is for investigating http://crbug.com/415059 and
354 // should be removed once it is fixed.
355 CHECK_LT(routing_id_highmark_, frame_routing_id);
356 routing_id_highmark_ = frame_routing_id;
358 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
359 // We can receive a GetServiceProviderForFrame message for a frame not yet
360 // created due to a race between the message and a ViewMsg_New IPC that
361 // triggers creation of the RenderFrame we want.
362 if (!frame) {
363 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
364 frame_routing_id, services.Pass(), exposed_services.Pass());
365 return;
368 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
371 private:
372 int32_t routing_id_highmark_;
375 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
376 mojo::BindToRequest(new RenderFrameSetupImpl(), &request);
379 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
380 blink::WebGraphicsContext3D::Attributes attributes;
381 attributes.shareResources = true;
382 attributes.depth = false;
383 attributes.stencil = false;
384 attributes.antialias = false;
385 attributes.noAutomaticFlushes = true;
386 return attributes;
389 } // namespace
391 // For measuring memory usage after each task. Behind a command line flag.
392 class MemoryObserver : public base::MessageLoop::TaskObserver {
393 public:
394 MemoryObserver() {}
395 ~MemoryObserver() override {}
397 void WillProcessTask(const base::PendingTask& pending_task) override {}
399 void DidProcessTask(const base::PendingTask& pending_task) override {
400 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
403 private:
404 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
407 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
408 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
409 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
410 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
413 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
415 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
416 const std::string& host, size_t view_count) {
417 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
418 switches::kDisableHistogramCustomizer)) {
419 return;
421 // Check if all RenderViews are displaying a page from the same host. If there
422 // is only one RenderView, the common host is this view's host. If there are
423 // many, check if this one shares the common host of the other
424 // RenderViews. It's ok to not detect some cases where the RenderViews share a
425 // common host. This information is only used for producing custom histograms.
426 if (view_count == 1)
427 SetCommonHost(host);
428 else if (host != common_host_)
429 SetCommonHost(std::string());
432 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
433 const char* histogram_name) const {
434 std::string name(histogram_name);
435 if (!common_host_histogram_suffix_.empty() &&
436 custom_histograms_.find(name) != custom_histograms_.end())
437 name += common_host_histogram_suffix_;
438 return name;
441 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
442 const std::string& host) {
443 if (host != common_host_) {
444 common_host_ = host;
445 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
446 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
450 RenderThreadImpl* RenderThreadImpl::current() {
451 return lazy_tls.Pointer()->Get();
454 RenderThreadImpl::RenderThreadImpl(const InProcessChildThreadParams& params)
455 : ChildThreadImpl(Options::Builder()
456 .InBrowserProcess(params)
457 .UseMojoChannel(ShouldUseMojoChannel())
458 .Build()) {
459 Init();
462 // When we run plugins in process, we actually run them on the render thread,
463 // which means that we need to make the render thread pump UI events.
464 RenderThreadImpl::RenderThreadImpl(
465 scoped_ptr<base::MessageLoop> main_message_loop)
466 : ChildThreadImpl(Options::Builder()
467 .UseMojoChannel(ShouldUseMojoChannel())
468 .Build()),
469 main_message_loop_(main_message_loop.Pass()) {
470 Init();
473 void RenderThreadImpl::Init() {
474 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
476 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
477 base::PlatformThread::CurrentId(),
478 kTraceEventRendererMainThreadSortIndex);
480 #if defined(OS_MACOSX) || defined(OS_ANDROID)
481 // On Mac and Android, the select popups are rendered by the browser.
482 blink::WebView::setUseExternalPopupMenus(true);
483 #endif
485 lazy_tls.Pointer()->Set(this);
487 // Register this object as the main thread.
488 ChildProcess::current()->set_main_thread(this);
490 // In single process the single process is all there is.
491 suspend_webkit_shared_timer_ = true;
492 notify_webkit_of_modal_loop_ = true;
493 webkit_shared_timer_suspended_ = false;
494 widget_count_ = 0;
495 hidden_widget_count_ = 0;
496 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
497 idle_notifications_to_skip_ = 0;
498 layout_test_mode_ = false;
500 appcache_dispatcher_.reset(
501 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
502 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
503 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
504 thread_safe_sender()));
505 renderer_scheduler_ = scheduler::RendererScheduler::Create();
506 channel()->SetListenerTaskRunner(renderer_scheduler_->DefaultTaskRunner());
507 main_thread_cache_storage_dispatcher_.reset(
508 new CacheStorageDispatcher(thread_safe_sender()));
509 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
511 // Note: This may reorder messages from the ResourceDispatcher with respect to
512 // other subsystems.
513 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
514 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
515 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
516 kMaxResourceRequestsPerFlushWhenThrottled));
517 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
519 media_stream_center_ = NULL;
521 db_message_filter_ = new DBMessageFilter();
522 AddFilter(db_message_filter_.get());
524 vc_manager_.reset(new VideoCaptureImplManager());
525 AddFilter(vc_manager_->video_capture_message_filter());
527 browser_plugin_manager_.reset(new BrowserPluginManager());
528 AddObserver(browser_plugin_manager_.get());
530 #if defined(ENABLE_WEBRTC)
531 peer_connection_tracker_.reset(new PeerConnectionTracker());
532 AddObserver(peer_connection_tracker_.get());
534 p2p_socket_dispatcher_ =
535 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
536 AddFilter(p2p_socket_dispatcher_.get());
538 webrtc_identity_service_.reset(new WebRTCIdentityService());
540 aec_dump_message_filter_ =
541 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
542 message_loop()->message_loop_proxy());
543 AddFilter(aec_dump_message_filter_.get());
545 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
546 p2p_socket_dispatcher_.get()));
547 #endif // defined(ENABLE_WEBRTC)
549 audio_input_message_filter_ =
550 new AudioInputMessageFilter(GetIOMessageLoopProxy());
551 AddFilter(audio_input_message_filter_.get());
553 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
554 AddFilter(audio_message_filter_.get());
556 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
557 AddFilter(midi_message_filter_.get());
559 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
561 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
563 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
565 GetContentClient()->renderer()->RenderThreadStarted();
567 InitSkiaEventTracer();
569 const base::CommandLine& command_line =
570 *base::CommandLine::ForCurrentProcess();
572 is_impl_side_painting_enabled_ =
573 !command_line.HasSwitch(switches::kDisableImplSidePainting);
574 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
575 is_impl_side_painting_enabled_);
577 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
578 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
580 #if defined(OS_MACOSX) && !defined(OS_IOS)
581 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
582 if (is_elastic_overscroll_enabled_) {
583 base::ScopedCFTypeRef<CFStringRef> key(
584 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
585 Boolean key_exists = false;
586 Boolean value = CFPreferencesGetAppBooleanValue(
587 key, kCFPreferencesCurrentApplication, &key_exists);
588 if (key_exists && !value)
589 is_elastic_overscroll_enabled_ = false;
591 #else
592 is_elastic_overscroll_enabled_ = false;
593 #endif
595 std::string image_texture_target_string =
596 command_line.GetSwitchValueASCII(switches::kUseImageTextureTarget);
597 bool parsed_image_texture_target = base::StringToUint(
598 image_texture_target_string, &use_image_texture_target_);
599 DCHECK(parsed_image_texture_target);
601 if (command_line.HasSwitch(switches::kDisableLCDText)) {
602 is_lcd_text_enabled_ = false;
603 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
604 is_lcd_text_enabled_ = true;
605 } else {
606 #if defined(OS_ANDROID)
607 is_lcd_text_enabled_ = false;
608 #else
609 is_lcd_text_enabled_ = true;
610 #endif
613 is_gpu_rasterization_enabled_ =
614 command_line.HasSwitch(switches::kEnableGpuRasterization);
615 is_gpu_rasterization_forced_ =
616 command_line.HasSwitch(switches::kForceGpuRasterization);
618 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
619 std::string string_value = command_line.GetSwitchValueASCII(
620 switches::kGpuRasterizationMSAASampleCount);
621 bool parsed_msaa_sample_count =
622 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
623 DCHECK(parsed_msaa_sample_count) << string_value;
624 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
625 } else {
626 gpu_rasterization_msaa_sample_count_ = 0;
629 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
630 is_distance_field_text_enabled_ = false;
631 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
632 is_distance_field_text_enabled_ = true;
633 } else {
634 is_distance_field_text_enabled_ = false;
637 // Note that under Linux, the media library will normally already have
638 // been initialized by the Zygote before this instance became a Renderer.
639 base::FilePath media_path;
640 PathService::Get(DIR_MEDIA_LIBS, &media_path);
641 if (!media_path.empty())
642 media::InitializeMediaLibrary(media_path);
644 memory_pressure_listener_.reset(new base::MemoryPressureListener(
645 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
647 compositor_task_graph_runner_.reset(new cc::TaskGraphRunner);
649 is_gather_pixel_refs_enabled_ = false;
651 if (is_impl_side_painting_enabled_) {
652 int num_raster_threads = 0;
653 std::string string_value =
654 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
655 bool parsed_num_raster_threads =
656 base::StringToInt(string_value, &num_raster_threads);
657 DCHECK(parsed_num_raster_threads) << string_value;
658 DCHECK_GT(num_raster_threads, 0);
660 // Note: Currently, gathering of pixel refs when using a single
661 // raster thread doesn't provide any benefit. This might change
662 // in the future but we avoid it for now to reduce the cost of
663 // Picture::Create.
664 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
666 while (compositor_raster_threads_.size() <
667 static_cast<size_t>(num_raster_threads)) {
668 scoped_ptr<CompositorRasterThread> raster_thread(
669 new CompositorRasterThread(
670 compositor_task_graph_runner_.get(),
671 base::StringPrintf(
672 "CompositorTileWorker%u",
673 static_cast<unsigned>(compositor_raster_threads_.size() + 1))
674 .c_str()));
675 raster_thread->Start();
676 #if defined(OS_ANDROID) || defined(OS_LINUX)
677 if (!command_line.HasSwitch(
678 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
679 raster_thread->SetThreadPriority(base::ThreadPriority::BACKGROUND);
681 #endif
682 compositor_raster_threads_.push_back(raster_thread.Pass());
686 // In single process, browser main loop set up the discardable memory
687 // allocator.
688 if (!command_line.HasSwitch(switches::kSingleProcess)) {
689 base::DiscardableMemoryAllocator::SetInstance(
690 ChildThreadImpl::discardable_shared_memory_manager());
693 service_registry()->AddService<RenderFrameSetup>(
694 base::Bind(CreateRenderFrameSetup));
696 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
699 RenderThreadImpl::~RenderThreadImpl() {
702 void RenderThreadImpl::Shutdown() {
703 FOR_EACH_OBSERVER(
704 RenderProcessObserver, observers_, OnRenderProcessShutdown());
706 ChildThreadImpl::Shutdown();
708 if (memory_observer_) {
709 message_loop()->RemoveTaskObserver(memory_observer_.get());
710 memory_observer_.reset();
713 // Wait for all databases to be closed.
714 if (blink_platform_impl_) {
715 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
716 // processing timer events while we're already in the process of shutting
717 // down blink, put a ScopePageLoadDeferrer on the stack.
718 WebView::willEnterModalLoop();
719 blink_platform_impl_->web_database_observer_impl()
720 ->WaitForAllDatabasesToClose();
721 WebView::didExitModalLoop();
724 // Shutdown in reverse of the initialization order.
725 if (devtools_agent_message_filter_.get()) {
726 RemoveFilter(devtools_agent_message_filter_.get());
727 devtools_agent_message_filter_ = NULL;
730 RemoveFilter(audio_input_message_filter_.get());
731 audio_input_message_filter_ = NULL;
733 #if defined(ENABLE_WEBRTC)
734 RTCPeerConnectionHandler::DestructAllHandlers();
735 // |peer_connection_factory_| cannot be deleted until after the main message
736 // loop has been destroyed. This is because there may be pending tasks that
737 // hold on to objects produced by the PC factory that depend on threads owned
738 // by the PC factory. Once those tasks have been freed, the factory can be
739 // deleted.
740 #endif
741 RemoveFilter(vc_manager_->video_capture_message_filter());
742 vc_manager_.reset();
744 RemoveFilter(db_message_filter_.get());
745 db_message_filter_ = NULL;
747 // Shutdown the file thread if it's running.
748 if (file_thread_)
749 file_thread_->Stop();
751 if (compositor_message_filter_.get()) {
752 RemoveFilter(compositor_message_filter_.get());
753 compositor_message_filter_ = NULL;
756 media_thread_.reset();
758 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
759 RemoveFilter(audio_message_filter_.get());
760 audio_message_filter_ = NULL;
762 compositor_thread_.reset();
764 // Shutdown raster threads.
765 compositor_task_graph_runner_->Shutdown();
766 while (!compositor_raster_threads_.empty()) {
767 compositor_raster_threads_.back()->Join();
768 compositor_raster_threads_.pop_back();
770 compositor_task_graph_runner_.reset();
772 main_input_callback_.Cancel();
773 input_handler_manager_.reset();
774 if (input_event_filter_.get()) {
775 RemoveFilter(input_event_filter_.get());
776 input_event_filter_ = NULL;
779 // RemoveEmbeddedWorkerRoute may be called while deleting
780 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
781 // RenderThreadImpl.
782 embedded_worker_dispatcher_.reset();
784 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
785 // hold pointers to V8 objects (e.g., via pending requests).
786 main_thread_indexed_db_dispatcher_.reset();
788 main_thread_compositor_task_runner_ = NULL;
790 // Context providers must be released prior to destroying the GPU channel.
791 gpu_va_context_provider_ = nullptr;
793 if (gpu_channel_.get())
794 gpu_channel_->DestroyChannel();
796 // TODO(port)
797 #if defined(OS_WIN)
798 // Clean up plugin channels before this thread goes away.
799 NPChannelBase::CleanupChannels();
800 #endif
802 // Shut down the message loop and the renderer scheduler before shutting down
803 // Blink. This prevents a scenario where a pending task in the message loop
804 // accesses Blink objects after Blink shuts down.
805 // This must be at the very end of the shutdown sequence. You must not touch
806 // the message loop after this.
807 renderer_scheduler_->Shutdown();
808 main_message_loop_.reset();
809 if (blink_platform_impl_)
810 blink::shutdown();
812 lazy_tls.Pointer()->Set(NULL);
815 bool RenderThreadImpl::Send(IPC::Message* msg) {
816 // Certain synchronous messages cannot always be processed synchronously by
817 // the browser, e.g., putting up UI and waiting for the user. This could cause
818 // a complete hang of Chrome if a windowed plugin is trying to communicate
819 // with the renderer thread since the browser's UI thread could be stuck
820 // (within a Windows API call) trying to synchronously communicate with the
821 // plugin. The remedy is to pump messages on this thread while the browser
822 // is processing this request. This creates an opportunity for re-entrancy
823 // into WebKit, so we need to take care to disable callbacks, timers, and
824 // pending network loads that could trigger such callbacks.
825 bool pumping_events = false;
826 if (msg->is_sync()) {
827 if (msg->is_caller_pumping_messages()) {
828 pumping_events = true;
832 bool suspend_webkit_shared_timer = true; // default value
833 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
835 bool notify_webkit_of_modal_loop = true; // default value
836 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
838 #if defined(ENABLE_PLUGINS)
839 int render_view_id = MSG_ROUTING_NONE;
840 #endif
842 if (pumping_events) {
843 if (suspend_webkit_shared_timer) {
844 // TODO(alexclarke): Remove the shared timer.
845 blink_platform_impl_->SuspendSharedTimer();
846 renderer_scheduler_->SuspendTimerQueue();
849 if (notify_webkit_of_modal_loop)
850 WebView::willEnterModalLoop();
851 #if defined(ENABLE_PLUGINS)
852 RenderViewImpl* render_view =
853 RenderViewImpl::FromRoutingID(msg->routing_id());
854 if (render_view) {
855 render_view_id = msg->routing_id();
856 PluginChannelHost::Broadcast(
857 new PluginMsg_SignalModalDialogEvent(render_view_id));
859 #endif
862 bool rv = ChildThreadImpl::Send(msg);
864 if (pumping_events) {
865 #if defined(ENABLE_PLUGINS)
866 if (render_view_id != MSG_ROUTING_NONE) {
867 PluginChannelHost::Broadcast(
868 new PluginMsg_ResetModalDialogEvent(render_view_id));
870 #endif
872 if (notify_webkit_of_modal_loop)
873 WebView::didExitModalLoop();
875 if (suspend_webkit_shared_timer) {
876 // TODO(alexclarke): Remove the shared timer.
877 blink_platform_impl_->ResumeSharedTimer();
878 renderer_scheduler_->ResumeTimerQueue();
882 return rv;
885 scoped_refptr<base::SingleThreadTaskRunner> RenderThreadImpl::GetTaskRunner() {
886 return GetRendererScheduler()->DefaultTaskRunner();
889 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
890 return channel();
893 std::string RenderThreadImpl::GetLocale() {
894 // The browser process should have passed the locale to the renderer via the
895 // --lang command line flag.
896 const base::CommandLine& parsed_command_line =
897 *base::CommandLine::ForCurrentProcess();
898 const std::string& lang =
899 parsed_command_line.GetSwitchValueASCII(switches::kLang);
900 DCHECK(!lang.empty());
901 return lang;
904 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
905 return sync_message_filter();
908 scoped_refptr<base::MessageLoopProxy>
909 RenderThreadImpl::GetIOMessageLoopProxy() {
910 return ChildProcess::current()->io_message_loop_proxy();
913 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
914 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
915 PendingRenderFrameConnectMap::iterator it =
916 pending_render_frame_connects_.find(routing_id);
917 if (it == pending_render_frame_connects_.end())
918 return;
920 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
921 if (!frame)
922 return;
924 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
925 mojo::InterfaceRequest<mojo::ServiceProvider> services(
926 connection->services().Pass());
927 mojo::ServiceProviderPtr exposed_services(
928 connection->exposed_services().Pass());
929 exposed_services.set_error_handler(nullptr);
930 pending_render_frame_connects_.erase(it);
932 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
935 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
936 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
939 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
940 IPC::Listener* listener) {
941 AddRoute(routing_id, listener);
942 if (devtools_agent_message_filter_.get()) {
943 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
944 routing_id);
948 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
949 RemoveRoute(routing_id);
950 if (devtools_agent_message_filter_.get()) {
951 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
952 routing_id);
956 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
957 int routing_id,
958 mojo::InterfaceRequest<mojo::ServiceProvider> services,
959 mojo::ServiceProviderPtr exposed_services) {
960 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
961 pending_render_frame_connects_.insert(std::make_pair(
962 routing_id,
963 make_scoped_refptr(new PendingRenderFrameConnect(
964 routing_id, services.Pass(), exposed_services.Pass()))));
965 CHECK(result.second) << "Inserting a duplicate item.";
968 int RenderThreadImpl::GenerateRoutingID() {
969 int routing_id = MSG_ROUTING_NONE;
970 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
971 return routing_id;
974 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
975 channel()->AddFilter(filter);
978 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
979 channel()->RemoveFilter(filter);
982 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
983 observers_.AddObserver(observer);
986 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
987 observers_.RemoveObserver(observer);
990 void RenderThreadImpl::SetResourceDispatcherDelegate(
991 ResourceDispatcherDelegate* delegate) {
992 resource_dispatcher()->set_delegate(delegate);
995 void RenderThreadImpl::SetResourceDispatchTaskQueue(
996 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
997 // Add a filter that forces resource messages to be dispatched via a
998 // particular task runner.
999 resource_scheduling_filter_ =
1000 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
1001 channel()->AddFilter(resource_scheduling_filter_.get());
1003 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1004 // same queue to ensure tasks are executed in the expected order.
1005 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1006 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1009 void RenderThreadImpl::EnsureWebKitInitialized() {
1010 if (blink_platform_impl_)
1011 return;
1013 const base::CommandLine& command_line =
1014 *base::CommandLine::ForCurrentProcess();
1016 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1017 if (command_line.HasSwitch(switches::kEnableVtune))
1018 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1019 #endif
1021 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1023 blink_platform_impl_.reset(
1024 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1025 blink::initialize(blink_platform_impl_.get());
1027 v8::Isolate* isolate = blink::mainThreadIsolate();
1028 isolate->SetCreateHistogramFunction(CreateHistogram);
1029 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1031 main_thread_compositor_task_runner_ =
1032 renderer_scheduler_->CompositorTaskRunner();
1034 main_input_callback_.Reset(
1035 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1036 base::Unretained(this)));
1038 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1040 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1041 if (enable) {
1042 #if defined(OS_ANDROID)
1043 if (SynchronousCompositorFactory* factory =
1044 SynchronousCompositorFactory::GetInstance())
1045 compositor_message_loop_proxy_ =
1046 factory->GetCompositorMessageLoop();
1047 #endif
1048 if (!compositor_message_loop_proxy_.get()) {
1049 compositor_thread_.reset(new base::Thread("Compositor"));
1050 compositor_thread_->Start();
1051 #if defined(OS_ANDROID)
1052 compositor_thread_->SetPriority(base::ThreadPriority::DISPLAY);
1053 #endif
1054 compositor_message_loop_proxy_ =
1055 compositor_thread_->message_loop_proxy();
1056 compositor_message_loop_proxy_->PostTask(
1057 FROM_HERE,
1058 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1059 false));
1062 InputHandlerManagerClient* input_handler_manager_client = NULL;
1063 #if defined(OS_ANDROID)
1064 if (SynchronousCompositorFactory* factory =
1065 SynchronousCompositorFactory::GetInstance()) {
1066 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1068 #endif
1069 if (!input_handler_manager_client) {
1070 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1071 new InputEventFilter(main_input_callback_.callback(),
1072 main_thread_compositor_task_runner_,
1073 compositor_message_loop_proxy_));
1074 input_handler_manager_client = compositor_input_event_filter.get();
1075 input_event_filter_ = compositor_input_event_filter;
1077 input_handler_manager_.reset(new InputHandlerManager(
1078 compositor_message_loop_proxy_, input_handler_manager_client,
1079 renderer_scheduler_.get()));
1082 if (!input_event_filter_.get()) {
1083 // Always provide an input event filter implementation to ensure consistent
1084 // input event scheduling and prioritization.
1085 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1086 // MainThreadInputEventFilter, crbug.com/436057.
1087 input_event_filter_ = new MainThreadInputEventFilter(
1088 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1090 AddFilter(input_event_filter_.get());
1092 scoped_refptr<base::MessageLoopProxy> compositor_impl_side_loop;
1093 if (enable)
1094 compositor_impl_side_loop = compositor_message_loop_proxy_;
1095 else
1096 compositor_impl_side_loop = base::MessageLoopProxy::current();
1098 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1099 compositor_impl_side_loop.get());
1100 AddFilter(compositor_message_filter_.get());
1102 RenderThreadImpl::RegisterSchemes();
1104 EnableBlinkPlatformLogChannels(
1105 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1107 if (!media::IsMediaLibraryInitialized()) {
1108 WebRuntimeFeatures::enableWebAudio(false);
1111 RenderMediaClient::Initialize();
1113 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1115 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1116 AddFilter(devtools_agent_message_filter_.get());
1118 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1120 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1121 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1123 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1125 // Limit use of the scaled image cache to when deferred image decoding is
1126 // enabled.
1127 if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
1128 !is_impl_side_painting_enabled_)
1129 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1131 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1132 kImageCacheSingleAllocationByteLimit);
1134 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1135 memory_observer_.reset(new MemoryObserver());
1136 message_loop()->AddTaskObserver(memory_observer_.get());
1139 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1140 std::string allowed_ports =
1141 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1142 net::SetExplicitlyAllowedPorts(allowed_ports);
1146 void RenderThreadImpl::RegisterSchemes() {
1147 // swappedout: pages should not be accessible, and should also
1148 // be treated as empty documents that can commit synchronously.
1149 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1150 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1151 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1154 void RenderThreadImpl::NotifyTimezoneChange() {
1155 NotifyTimezoneChangeOnThisThread();
1156 RenderThread::Get()->PostTaskToAllWebWorkers(
1157 base::Bind(&NotifyTimezoneChangeOnThisThread));
1160 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1161 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1164 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1165 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1168 scoped_ptr<base::SharedMemory>
1169 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1170 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1173 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1174 return shared_bitmap_manager();
1177 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1178 WebScriptController::registerExtension(extension);
1181 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1182 idle_notification_delay_in_ms_ = initial_delay_ms;
1183 idle_timer_.Stop();
1184 idle_timer_.Start(FROM_HERE,
1185 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1186 this, &RenderThreadImpl::IdleHandler);
1189 void RenderThreadImpl::IdleHandler() {
1190 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1191 GetContentClient()->renderer()->
1192 RunIdleHandlerWhenWidgetsHidden();
1193 if (run_in_foreground_tab) {
1194 if (idle_notifications_to_skip_ > 0) {
1195 --idle_notifications_to_skip_;
1196 } else {
1197 base::allocator::ReleaseFreeMemory();
1198 discardable_shared_memory_manager()->ReleaseFreeMemory();
1200 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1201 return;
1204 base::allocator::ReleaseFreeMemory();
1205 discardable_shared_memory_manager()->ReleaseFreeMemory();
1207 // Continue the idle timer if the webkit shared timer is not suspended or
1208 // something is left to do.
1209 bool continue_timer = !webkit_shared_timer_suspended_;
1211 if (blink::mainThreadIsolate() &&
1212 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1213 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1214 continue_timer = true;
1217 // Schedule next invocation. When the tab is originally hidden, an invocation
1218 // is scheduled for kInitialIdleHandlerDelayMs in
1219 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1220 // After that, idle calls can be much less frequent, so run at a maximum of
1221 // once every kLongIdleHandlerDelayMs.
1222 // Dampen the delay using the algorithm (if delay is in seconds):
1223 // delay = delay + 1 / (delay + 2)
1224 // Using floor(delay) has a dampening effect such as:
1225 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1226 // If the delay is in milliseconds, the above formula is equivalent to:
1227 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1228 // which is equivalent to
1229 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1230 if (continue_timer) {
1231 ScheduleIdleHandler(
1232 std::max(kLongIdleHandlerDelayMs,
1233 idle_notification_delay_in_ms_ +
1234 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1236 } else {
1237 idle_timer_.Stop();
1240 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1243 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1244 return idle_notification_delay_in_ms_;
1247 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1248 int64 idle_notification_delay_in_ms) {
1249 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1252 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1253 child_histogram_message_filter()->SendHistograms(sequence_number);
1256 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1257 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1260 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1261 bool result = false;
1262 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1263 return result;
1266 void RenderThreadImpl::PostponeIdleNotification() {
1267 idle_notifications_to_skip_ = 2;
1270 scoped_refptr<media::GpuVideoAcceleratorFactories>
1271 RenderThreadImpl::GetGpuFactories() {
1272 DCHECK(IsMainThread());
1274 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1275 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1276 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1277 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1278 GetMediaThreadTaskRunner();
1279 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1280 if (!gpu_va_context_provider_.get() ||
1281 gpu_va_context_provider_->DestroyedOnMainThread()) {
1282 if (!gpu_channel_host.get()) {
1283 gpu_channel_host = EstablishGpuChannelSync(
1284 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1286 blink::WebGraphicsContext3D::Attributes attributes;
1287 bool lose_context_when_out_of_memory = false;
1288 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1289 make_scoped_ptr(
1290 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1291 gpu_channel_host.get(),
1292 attributes,
1293 lose_context_when_out_of_memory,
1294 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1295 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1296 NULL)),
1297 "GPU-VideoAccelerator-Offscreen");
1300 if (gpu_va_context_provider_.get()) {
1301 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1302 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_);
1304 return gpu_factories;
1307 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1308 RenderThreadImpl::CreateOffscreenContext3d() {
1309 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1310 bool lose_context_when_out_of_memory = true;
1312 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1313 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1314 return make_scoped_ptr(
1315 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1316 gpu_channel_host.get(),
1317 attributes,
1318 lose_context_when_out_of_memory,
1319 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1320 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1321 NULL));
1324 scoped_refptr<cc_blink::ContextProviderWebContext>
1325 RenderThreadImpl::SharedMainThreadContextProvider() {
1326 DCHECK(IsMainThread());
1327 if (!shared_main_thread_contexts_.get() ||
1328 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1329 shared_main_thread_contexts_ = NULL;
1330 #if defined(OS_ANDROID)
1331 if (SynchronousCompositorFactory* factory =
1332 SynchronousCompositorFactory::GetInstance()) {
1333 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1334 GetOffscreenAttribs(), "Offscreen-MainThread");
1336 #endif
1337 if (!shared_main_thread_contexts_.get()) {
1338 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1339 CreateOffscreenContext3d(), "Offscreen-MainThread");
1341 if (shared_main_thread_contexts_.get() &&
1342 !shared_main_thread_contexts_->BindToCurrentThread())
1343 shared_main_thread_contexts_ = NULL;
1345 return shared_main_thread_contexts_;
1348 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1349 if (!audio_renderer_mixer_manager_) {
1350 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1351 GetAudioHardwareConfig()));
1354 return audio_renderer_mixer_manager_.get();
1357 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1358 if (!audio_hardware_config_) {
1359 media::AudioParameters input_params;
1360 media::AudioParameters output_params;
1361 Send(new ViewHostMsg_GetAudioHardwareConfig(
1362 &input_params, &output_params));
1364 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1365 input_params, output_params));
1368 return audio_hardware_config_.get();
1371 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1372 return ChildProcess::current()->GetShutDownEvent();
1375 #if defined(OS_WIN)
1376 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1377 const base::string16& str) {
1378 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1381 #endif // OS_WIN
1383 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1384 return service_registry();
1387 bool RenderThreadImpl::IsImplSidePaintingEnabled() {
1388 return is_impl_side_painting_enabled_;
1391 bool RenderThreadImpl::IsGpuRasterizationForced() {
1392 return is_gpu_rasterization_forced_;
1395 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1396 return is_gpu_rasterization_enabled_;
1399 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1400 return gpu_rasterization_msaa_sample_count_;
1403 bool RenderThreadImpl::IsLcdTextEnabled() {
1404 return is_lcd_text_enabled_;
1407 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1408 return is_distance_field_text_enabled_;
1411 bool RenderThreadImpl::IsZeroCopyEnabled() {
1412 return is_zero_copy_enabled_;
1415 bool RenderThreadImpl::IsOneCopyEnabled() {
1416 return is_one_copy_enabled_;
1419 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1420 return is_elastic_overscroll_enabled_;
1423 bool RenderThreadImpl::UseSingleThreadScheduler() {
1424 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
1425 return !cmd->HasSwitch(switches::kDisableSingleThreadProxyScheduler);
1428 uint32 RenderThreadImpl::GetImageTextureTarget() {
1429 return use_image_texture_target_;
1432 scoped_refptr<base::SingleThreadTaskRunner>
1433 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1434 return main_thread_compositor_task_runner_;
1437 scoped_refptr<base::SingleThreadTaskRunner>
1438 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1439 return compositor_message_loop_proxy_;
1442 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1443 return gpu_memory_buffer_manager();
1446 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1447 return renderer_scheduler_.get();
1450 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1451 return SharedMainThreadContextProvider().get();
1454 scoped_ptr<cc::BeginFrameSource>
1455 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1456 #if defined(OS_ANDROID)
1457 if (SynchronousCompositorFactory* factory =
1458 SynchronousCompositorFactory::GetInstance()) {
1459 return factory->CreateExternalBeginFrameSource(routing_id);
1461 #endif
1462 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1463 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1466 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1467 return compositor_task_graph_runner_.get();
1470 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1471 return is_gather_pixel_refs_enabled_;
1474 bool RenderThreadImpl::IsMainThread() {
1475 return !!current();
1478 base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1479 return message_loop();
1482 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1483 return io_message_loop_proxy_;
1486 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1487 size_t size) {
1488 return scoped_ptr<base::SharedMemory>(
1489 HostAllocateSharedMemoryBuffer(size));
1492 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1493 int32 surface_id,
1494 const GPUCreateCommandBufferConfig& init_params,
1495 int32 route_id) {
1496 TRACE_EVENT1("gpu",
1497 "RenderThreadImpl::CreateViewCommandBuffer",
1498 "surface_id",
1499 surface_id);
1501 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1502 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1503 surface_id,
1504 init_params,
1505 route_id,
1506 &result);
1508 // Allow calling this from the compositor thread.
1509 thread_safe_sender()->Send(message);
1511 return result;
1514 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1515 suspend_webkit_shared_timer_ = false;
1518 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1519 notify_webkit_of_modal_loop_ = false;
1522 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1523 ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1524 RenderProcessObserver* observer;
1525 while ((observer = it.GetNext()) != NULL) {
1526 if (observer->OnControlMessageReceived(msg))
1527 return true;
1530 // Some messages are handled by delegates.
1531 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1532 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1533 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1534 return true;
1537 bool handled = true;
1538 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1539 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1540 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1541 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1542 OnSetZoomLevelForCurrentURL)
1543 // TODO(port): removed from render_messages_internal.h;
1544 // is there a new non-windows message I should add here?
1545 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1546 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1547 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1548 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1549 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1550 #if defined(OS_ANDROID)
1551 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1552 OnSetWebKitSharedTimersSuspended)
1553 #endif
1554 #if defined(OS_MACOSX)
1555 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1556 #endif
1557 #if defined(ENABLE_PLUGINS)
1558 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1559 #endif
1560 IPC_MESSAGE_UNHANDLED(handled = false)
1561 IPC_END_MESSAGE_MAP()
1562 return handled;
1565 void RenderThreadImpl::OnCreateNewFrame(
1566 int routing_id,
1567 int parent_routing_id,
1568 int proxy_routing_id,
1569 const FrameReplicationState& replicated_state,
1570 FrameMsg_NewFrame_WidgetParams params) {
1571 CompositorDependencies* compositor_deps = this;
1572 RenderFrameImpl::CreateFrame(routing_id, parent_routing_id, proxy_routing_id,
1573 replicated_state, compositor_deps, params);
1576 void RenderThreadImpl::OnCreateNewFrameProxy(
1577 int routing_id,
1578 int parent_routing_id,
1579 int render_view_routing_id,
1580 const FrameReplicationState& replicated_state) {
1581 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1582 render_view_routing_id, replicated_state);
1585 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1586 const std::string& host,
1587 double zoom_level) {
1588 RenderViewZoomer zoomer(scheme, host, zoom_level);
1589 RenderView::ForEach(&zoomer);
1592 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1593 EnsureWebKitInitialized();
1594 CompositorDependencies* compositor_deps = this;
1595 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1596 RenderViewImpl::Create(params, compositor_deps, false);
1599 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1600 CauseForGpuLaunch cause_for_gpu_launch) {
1601 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1603 if (gpu_channel_.get()) {
1604 // Do nothing if we already have a GPU channel or are already
1605 // establishing one.
1606 if (!gpu_channel_->IsLost())
1607 return gpu_channel_.get();
1609 // Recreate the channel if it has been lost.
1610 gpu_channel_ = NULL;
1613 // Ask the browser for the channel name.
1614 int client_id = 0;
1615 IPC::ChannelHandle channel_handle;
1616 gpu::GPUInfo gpu_info;
1617 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1618 &client_id,
1619 &channel_handle,
1620 &gpu_info)) ||
1621 #if defined(OS_POSIX)
1622 channel_handle.socket.fd == -1 ||
1623 #endif
1624 channel_handle.name.empty()) {
1625 // Otherwise cancel the connection.
1626 return NULL;
1629 GetContentClient()->SetGpuInfo(gpu_info);
1631 // Cache some variables that are needed on the compositor thread for our
1632 // implementation of GpuChannelHostFactory.
1633 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1635 gpu_channel_ =
1636 GpuChannelHost::Create(this,
1637 gpu_info,
1638 channel_handle,
1639 ChildProcess::current()->GetShutDownEvent(),
1640 gpu_memory_buffer_manager());
1641 return gpu_channel_.get();
1644 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1645 blink::WebMediaStreamCenterClient* client) {
1646 #if defined(OS_ANDROID)
1647 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1648 switches::kDisableWebRTC))
1649 return NULL;
1650 #endif
1652 #if defined(ENABLE_WEBRTC)
1653 if (!media_stream_center_) {
1654 media_stream_center_ = GetContentClient()->renderer()
1655 ->OverrideCreateWebMediaStreamCenter(client);
1656 if (!media_stream_center_) {
1657 scoped_ptr<MediaStreamCenter> media_stream_center(
1658 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1659 media_stream_center_ = media_stream_center.release();
1662 #endif
1663 return media_stream_center_;
1666 #if defined(ENABLE_WEBRTC)
1667 PeerConnectionDependencyFactory*
1668 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1669 return peer_connection_factory_.get();
1671 #endif
1673 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1674 if (!gpu_channel_.get())
1675 return NULL;
1677 if (gpu_channel_->IsLost())
1678 return NULL;
1680 return gpu_channel_.get();
1683 #if defined(ENABLE_PLUGINS)
1684 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1685 EnsureWebKitInitialized();
1686 // The call below will cause a GetPlugins call with refresh=true, but at this
1687 // point we already know that the browser has refreshed its list, so disable
1688 // refresh temporarily to prevent each renderer process causing the list to be
1689 // regenerated.
1690 blink_platform_impl_->set_plugin_refresh_allowed(false);
1691 blink::resetPluginCache(reload_pages);
1692 blink_platform_impl_->set_plugin_refresh_allowed(true);
1694 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1696 #endif
1698 void RenderThreadImpl::OnNetworkTypeChanged(
1699 net::NetworkChangeNotifier::ConnectionType type) {
1700 EnsureWebKitInitialized();
1701 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1702 WebNetworkStateNotifier::setOnLine(online);
1703 FOR_EACH_OBSERVER(
1704 RenderProcessObserver, observers_, NetworkStateChanged(online));
1705 WebNetworkStateNotifier::setWebConnectionType(
1706 NetConnectionTypeToWebConnectionType(type));
1709 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1710 GetContentClient()->SetActiveURL(data);
1711 CHECK(false);
1714 void RenderThreadImpl::OnUpdateTimezone() {
1715 if (!blink_platform_impl_)
1716 return;
1717 NotifyTimezoneChange();
1720 #if defined(OS_ANDROID)
1721 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1722 if (suspend_webkit_shared_timer_) {
1723 EnsureWebKitInitialized();
1724 // TODO(alexclarke): Remove the shared timer.
1725 if (suspend) {
1726 blink_platform_impl_->SuspendSharedTimer();
1727 renderer_scheduler_->SuspendTimerQueue();
1728 } else {
1729 blink_platform_impl_->ResumeSharedTimer();
1730 renderer_scheduler_->ResumeTimerQueue();
1732 webkit_shared_timer_suspended_ = suspend;
1735 #endif
1737 #if defined(OS_MACOSX)
1738 void RenderThreadImpl::OnUpdateScrollbarTheme(
1739 float initial_button_delay,
1740 float autoscroll_button_delay,
1741 bool jump_on_track_click,
1742 blink::ScrollerStyle preferred_scroller_style,
1743 bool redraw) {
1744 EnsureWebKitInitialized();
1745 static_cast<WebScrollbarBehaviorImpl*>(
1746 blink_platform_impl_->scrollbarBehavior())
1747 ->set_jump_on_track_click(jump_on_track_click);
1748 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1749 autoscroll_button_delay,
1750 preferred_scroller_style,
1751 redraw);
1753 #endif
1755 void RenderThreadImpl::OnCreateNewSharedWorker(
1756 const WorkerProcessMsg_CreateWorker_Params& params) {
1757 // EmbeddedSharedWorkerStub will self-destruct.
1758 new EmbeddedSharedWorkerStub(params.url,
1759 params.name,
1760 params.content_security_policy,
1761 params.security_policy_type,
1762 params.pause_on_start,
1763 params.route_id);
1766 void RenderThreadImpl::OnMemoryPressure(
1767 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1768 base::allocator::ReleaseFreeMemory();
1769 discardable_shared_memory_manager()->ReleaseFreeMemory();
1771 // Do not call into blink if it is not initialized.
1772 if (blink_platform_impl_) {
1773 blink::WebCache::pruneAll();
1775 if (blink::mainThreadIsolate()) {
1776 // Trigger full v8 garbage collection on memory pressure notifications.
1777 // This will potentially hang the renderer for a long time, however, when
1778 // we receive a memory pressure notification, we might be about to be
1779 // killed.
1780 blink::mainThreadIsolate()->LowMemoryNotification();
1781 RenderThread::Get()->PostTaskToAllWebWorkers(
1782 base::Bind(&LowMemoryNotificationOnThisThread));
1785 if (memory_pressure_level ==
1786 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1787 // Clear the image cache.
1788 blink::WebImageCache::clear();
1790 // Purge Skia font cache, by setting it to 0 and then again to the
1791 // previous limit.
1792 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1793 SkGraphics::SetFontCacheLimit(font_cache_limit);
1798 scoped_refptr<base::MessageLoopProxy>
1799 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1800 DCHECK(message_loop() == base::MessageLoop::current());
1801 if (!file_thread_) {
1802 file_thread_.reset(new base::Thread("Renderer::FILE"));
1803 file_thread_->Start();
1805 return file_thread_->message_loop_proxy();
1808 scoped_refptr<base::SingleThreadTaskRunner>
1809 RenderThreadImpl::GetMediaThreadTaskRunner() {
1810 DCHECK(message_loop() == base::MessageLoop::current());
1811 if (!media_thread_) {
1812 media_thread_.reset(new base::Thread("Media"));
1813 media_thread_->Start();
1815 #if defined(OS_ANDROID)
1816 renderer_demuxer_ = new RendererDemuxerAndroid();
1817 AddFilter(renderer_demuxer_.get());
1818 #endif
1820 return media_thread_->message_loop_proxy();
1823 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1824 blink_platform_impl_->sampleGamepads(*data);
1827 bool RenderThreadImpl::RendererIsHidden() const {
1828 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1831 void RenderThreadImpl::WidgetCreated() {
1832 bool renderer_was_hidden = RendererIsHidden();
1833 widget_count_++;
1834 if (renderer_was_hidden)
1835 OnRendererVisible();
1838 void RenderThreadImpl::WidgetDestroyed() {
1839 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1840 // unhidden before WidgetDestroyed is called.
1841 DCHECK_GT(widget_count_, 0);
1842 DCHECK_GT(widget_count_, hidden_widget_count_);
1843 widget_count_--;
1844 if (RendererIsHidden())
1845 OnRendererHidden();
1848 void RenderThreadImpl::WidgetHidden() {
1849 DCHECK_LT(hidden_widget_count_, widget_count_);
1850 hidden_widget_count_++;
1851 if (RendererIsHidden())
1852 OnRendererHidden();
1855 void RenderThreadImpl::WidgetRestored() {
1856 bool renderer_was_hidden = RendererIsHidden();
1857 DCHECK_GT(hidden_widget_count_, 0);
1858 hidden_widget_count_--;
1859 if (renderer_was_hidden)
1860 OnRendererVisible();
1863 void RenderThreadImpl::OnRendererHidden() {
1864 renderer_scheduler_->OnRendererHidden();
1866 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1867 // scheduled by the RendererScheduler - http://crbug.com/469210.
1868 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1869 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1872 void RenderThreadImpl::OnRendererVisible() {
1873 renderer_scheduler_->OnRendererVisible();
1875 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1876 return;
1878 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1881 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1882 int routing_id,
1883 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1884 mojo::ServiceProviderPtr exposed_services)
1885 : routing_id_(routing_id),
1886 services_(services.Pass()),
1887 exposed_services_(exposed_services.Pass()) {
1888 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1889 // is received. In that case, the RenderFrameHost should close the connection,
1890 // which is detected by setting an error handler on |exposed_services_|.
1891 exposed_services_.set_error_handler(this);
1894 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1897 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1898 size_t erased =
1899 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1900 routing_id_);
1901 DCHECK_EQ(1u, erased);
1904 } // namespace content