Remove GpuChannelHostFactory::GetMainLoop
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blobb0476c92140e9cef78a94e2b842f5ec1e16ea23b
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/icu/source/i18n/unicode/timezone.h"
141 #include "third_party/skia/include/core/SkGraphics.h"
142 #include "ui/base/layout.h"
143 #include "ui/base/ui_base_switches.h"
144 #include "v8/include/v8.h"
146 #if defined(OS_ANDROID)
147 #include <cpu-features.h>
148 #include "content/renderer/android/synchronous_compositor_factory.h"
149 #include "content/renderer/media/android/renderer_demuxer_android.h"
150 #endif
152 #if defined(OS_MACOSX)
153 #include "base/mac/mac_util.h"
154 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
155 #endif
157 #if defined(OS_POSIX)
158 #include "ipc/ipc_channel_posix.h"
159 #endif
161 #if defined(OS_WIN)
162 #include <windows.h>
163 #include <objbase.h>
164 #else
165 // TODO(port)
166 #include "content/child/npapi/np_channel_base.h"
167 #endif
169 #if defined(ENABLE_PLUGINS)
170 #include "content/renderer/npapi/plugin_channel_host.h"
171 #endif
173 #if defined(ENABLE_WEBRTC)
174 #include "content/renderer/media/peer_connection_tracker.h"
175 #include "content/renderer/media/rtc_peer_connection_handler.h"
176 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
177 #include "content/renderer/media/webrtc_identity_service.h"
178 #endif
180 #ifdef ENABLE_VTUNE_JIT_INTERFACE
181 #include "v8/src/third_party/vtune/v8-vtune.h"
182 #endif
184 using base::ThreadRestrictions;
185 using blink::WebDocument;
186 using blink::WebFrame;
187 using blink::WebNetworkStateNotifier;
188 using blink::WebRuntimeFeatures;
189 using blink::WebScriptController;
190 using blink::WebSecurityPolicy;
191 using blink::WebString;
192 using blink::WebView;
194 namespace content {
196 namespace {
198 const int64 kInitialIdleHandlerDelayMs = 1000;
199 const int64 kLongIdleHandlerDelayMs = 30*1000;
201 #if defined(OS_ANDROID)
202 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
203 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
204 // induced work takes but a fraction (~1/4) of the overall frame budget.
205 const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
206 #else
207 const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
208 #endif
209 const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
211 // Maximum allocation size allowed for image scaling filters that
212 // require pre-scaling. Skia will fallback to a filter that doesn't
213 // require pre-scaling if the default filter would require an
214 // allocation that exceeds this limit.
215 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
217 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
218 // incorrectly from the wrong thread.
219 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
220 lazy_tls = LAZY_INSTANCE_INITIALIZER;
222 class RenderViewZoomer : public RenderViewVisitor {
223 public:
224 RenderViewZoomer(const std::string& scheme,
225 const std::string& host,
226 double zoom_level) : scheme_(scheme),
227 host_(host),
228 zoom_level_(zoom_level) {
231 bool Visit(RenderView* render_view) override {
232 WebView* webview = render_view->GetWebView();
233 // Remote frames don't host documents.
234 // TODO(wjmaclean) Although it seems likely that a frame without a
235 // document can safely early-out here, we should confirm this is truly
236 // the case. https://crbug.com/477007
237 if (webview->mainFrame()->isWebRemoteFrame())
238 return true;
240 WebDocument document = webview->mainFrame()->document();
242 // Don't set zoom level for full-page plugin since they don't use the same
243 // zoom settings.
244 if (document.isPluginDocument())
245 return true;
246 GURL url(document.url());
247 // Empty scheme works as wildcard that matches any scheme,
248 if ((net::GetHostOrSpecFromURL(url) == host_) &&
249 (scheme_.empty() || scheme_ == url.scheme()) &&
250 !static_cast<RenderViewImpl*>(render_view)
251 ->uses_temporary_zoom_level()) {
252 webview->hidePopups();
253 webview->setZoomLevel(zoom_level_);
255 return true;
258 private:
259 const std::string scheme_;
260 const std::string host_;
261 const double zoom_level_;
263 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
266 class CompositorRasterThread : public base::SimpleThread {
267 public:
268 CompositorRasterThread(cc::TaskGraphRunner* task_graph_runner,
269 const std::string& name_prefix)
270 : base::SimpleThread(name_prefix),
271 task_graph_runner_(task_graph_runner) {}
273 // Overridden from base::SimpleThread:
274 void Run() override { task_graph_runner_->Run(); }
276 private:
277 cc::TaskGraphRunner* task_graph_runner_;
279 DISALLOW_COPY_AND_ASSIGN(CompositorRasterThread);
282 std::string HostToCustomHistogramSuffix(const std::string& host) {
283 if (host == "mail.google.com")
284 return ".gmail";
285 if (host == "docs.google.com" || host == "drive.google.com")
286 return ".docs";
287 if (host == "plus.google.com")
288 return ".plus";
289 return std::string();
292 void* CreateHistogram(
293 const char *name, int min, int max, size_t buckets) {
294 if (min <= 0)
295 min = 1;
296 std::string histogram_name;
297 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
298 if (render_thread_impl) { // Can be null in tests.
299 histogram_name = render_thread_impl->
300 histogram_customizer()->ConvertToCustomHistogramName(name);
301 } else {
302 histogram_name = std::string(name);
304 base::HistogramBase* histogram = base::Histogram::FactoryGet(
305 histogram_name, min, max, buckets,
306 base::Histogram::kUmaTargetedHistogramFlag);
307 return histogram;
310 void AddHistogramSample(void* hist, int sample) {
311 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
312 histogram->Add(sample);
315 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
316 const gfx::Size& size) {
317 return ChildThreadImpl::current()->shared_bitmap_manager()->
318 AllocateSharedBitmap(size);
321 void EnableBlinkPlatformLogChannels(const std::string& channels) {
322 if (channels.empty())
323 return;
324 base::StringTokenizer t(channels, ", ");
325 while (t.GetNext())
326 blink::enableLogChannel(t.token().c_str());
329 void NotifyTimezoneChangeOnThisThread() {
330 v8::Isolate* isolate = v8::Isolate::GetCurrent();
331 if (!isolate)
332 return;
333 v8::Date::DateTimeConfigurationChangeNotification(isolate);
336 void LowMemoryNotificationOnThisThread() {
337 v8::Isolate* isolate = v8::Isolate::GetCurrent();
338 if (!isolate)
339 return;
340 isolate->LowMemoryNotification();
343 class RenderFrameSetupImpl : public mojo::InterfaceImpl<RenderFrameSetup> {
344 public:
345 RenderFrameSetupImpl()
346 : routing_id_highmark_(-1) {
349 void ExchangeServiceProviders(
350 int32_t frame_routing_id,
351 mojo::InterfaceRequest<mojo::ServiceProvider> services,
352 mojo::ServiceProviderPtr exposed_services)
353 override {
354 // TODO(morrita): This is for investigating http://crbug.com/415059 and
355 // should be removed once it is fixed.
356 CHECK_LT(routing_id_highmark_, frame_routing_id);
357 routing_id_highmark_ = frame_routing_id;
359 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
360 // We can receive a GetServiceProviderForFrame message for a frame not yet
361 // created due to a race between the message and a ViewMsg_New IPC that
362 // triggers creation of the RenderFrame we want.
363 if (!frame) {
364 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
365 frame_routing_id, services.Pass(), exposed_services.Pass());
366 return;
369 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
372 private:
373 int32_t routing_id_highmark_;
376 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
377 mojo::BindToRequest(new RenderFrameSetupImpl(), &request);
380 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
381 blink::WebGraphicsContext3D::Attributes attributes;
382 attributes.shareResources = true;
383 attributes.depth = false;
384 attributes.stencil = false;
385 attributes.antialias = false;
386 attributes.noAutomaticFlushes = true;
387 return attributes;
390 } // namespace
392 // For measuring memory usage after each task. Behind a command line flag.
393 class MemoryObserver : public base::MessageLoop::TaskObserver {
394 public:
395 MemoryObserver() {}
396 ~MemoryObserver() override {}
398 void WillProcessTask(const base::PendingTask& pending_task) override {}
400 void DidProcessTask(const base::PendingTask& pending_task) override {
401 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
404 private:
405 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
408 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
409 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
410 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
411 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
414 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
416 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
417 const std::string& host, size_t view_count) {
418 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
419 switches::kDisableHistogramCustomizer)) {
420 return;
422 // Check if all RenderViews are displaying a page from the same host. If there
423 // is only one RenderView, the common host is this view's host. If there are
424 // many, check if this one shares the common host of the other
425 // RenderViews. It's ok to not detect some cases where the RenderViews share a
426 // common host. This information is only used for producing custom histograms.
427 if (view_count == 1)
428 SetCommonHost(host);
429 else if (host != common_host_)
430 SetCommonHost(std::string());
433 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
434 const char* histogram_name) const {
435 std::string name(histogram_name);
436 if (!common_host_histogram_suffix_.empty() &&
437 custom_histograms_.find(name) != custom_histograms_.end())
438 name += common_host_histogram_suffix_;
439 return name;
442 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
443 const std::string& host) {
444 if (host != common_host_) {
445 common_host_ = host;
446 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
447 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
451 RenderThreadImpl* RenderThreadImpl::current() {
452 return lazy_tls.Pointer()->Get();
455 RenderThreadImpl::RenderThreadImpl(const InProcessChildThreadParams& params)
456 : ChildThreadImpl(Options::Builder()
457 .InBrowserProcess(params)
458 .UseMojoChannel(ShouldUseMojoChannel())
459 .Build()) {
460 Init();
463 // When we run plugins in process, we actually run them on the render thread,
464 // which means that we need to make the render thread pump UI events.
465 RenderThreadImpl::RenderThreadImpl(
466 scoped_ptr<base::MessageLoop> main_message_loop)
467 : ChildThreadImpl(Options::Builder()
468 .UseMojoChannel(ShouldUseMojoChannel())
469 .Build()),
470 main_message_loop_(main_message_loop.Pass()) {
471 Init();
474 void RenderThreadImpl::Init() {
475 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
477 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
478 base::PlatformThread::CurrentId(),
479 kTraceEventRendererMainThreadSortIndex);
481 #if defined(OS_MACOSX) || defined(OS_ANDROID)
482 // On Mac and Android, the select popups are rendered by the browser.
483 blink::WebView::setUseExternalPopupMenus(true);
484 #endif
486 lazy_tls.Pointer()->Set(this);
488 // Register this object as the main thread.
489 ChildProcess::current()->set_main_thread(this);
491 // In single process the single process is all there is.
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;
792 shared_main_thread_contexts_ = nullptr;
794 if (gpu_channel_.get())
795 gpu_channel_->DestroyChannel();
797 // TODO(port)
798 #if defined(OS_WIN)
799 // Clean up plugin channels before this thread goes away.
800 NPChannelBase::CleanupChannels();
801 #endif
803 // Shut down the message loop and the renderer scheduler before shutting down
804 // Blink. This prevents a scenario where a pending task in the message loop
805 // accesses Blink objects after Blink shuts down.
806 // This must be at the very end of the shutdown sequence. You must not touch
807 // the message loop after this.
808 renderer_scheduler_->Shutdown();
809 main_message_loop_.reset();
810 if (blink_platform_impl_)
811 blink::shutdown();
813 lazy_tls.Pointer()->Set(NULL);
816 bool RenderThreadImpl::Send(IPC::Message* msg) {
817 // Certain synchronous messages cannot always be processed synchronously by
818 // the browser, e.g., putting up UI and waiting for the user. This could cause
819 // a complete hang of Chrome if a windowed plugin is trying to communicate
820 // with the renderer thread since the browser's UI thread could be stuck
821 // (within a Windows API call) trying to synchronously communicate with the
822 // plugin. The remedy is to pump messages on this thread while the browser
823 // is processing this request. This creates an opportunity for re-entrancy
824 // into WebKit, so we need to take care to disable callbacks, timers, and
825 // pending network loads that could trigger such callbacks.
826 bool pumping_events = false;
827 if (msg->is_sync()) {
828 if (msg->is_caller_pumping_messages()) {
829 pumping_events = true;
833 bool notify_webkit_of_modal_loop = true; // default value
834 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
836 #if defined(ENABLE_PLUGINS)
837 int render_view_id = MSG_ROUTING_NONE;
838 #endif
840 if (pumping_events) {
841 // TODO(alexclarke): Remove the shared timer.
842 blink_platform_impl_->SuspendSharedTimer();
843 renderer_scheduler_->SuspendTimerQueue();
845 if (notify_webkit_of_modal_loop)
846 WebView::willEnterModalLoop();
847 #if defined(ENABLE_PLUGINS)
848 RenderViewImpl* render_view =
849 RenderViewImpl::FromRoutingID(msg->routing_id());
850 if (render_view) {
851 render_view_id = msg->routing_id();
852 PluginChannelHost::Broadcast(
853 new PluginMsg_SignalModalDialogEvent(render_view_id));
855 #endif
858 bool rv = ChildThreadImpl::Send(msg);
860 if (pumping_events) {
861 #if defined(ENABLE_PLUGINS)
862 if (render_view_id != MSG_ROUTING_NONE) {
863 PluginChannelHost::Broadcast(
864 new PluginMsg_ResetModalDialogEvent(render_view_id));
866 #endif
868 if (notify_webkit_of_modal_loop)
869 WebView::didExitModalLoop();
871 // TODO(alexclarke): Remove the shared timer.
872 blink_platform_impl_->ResumeSharedTimer();
873 renderer_scheduler_->ResumeTimerQueue();
876 return rv;
879 scoped_refptr<base::SingleThreadTaskRunner> RenderThreadImpl::GetTaskRunner() {
880 return GetRendererScheduler()->DefaultTaskRunner();
883 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
884 return channel();
887 std::string RenderThreadImpl::GetLocale() {
888 // The browser process should have passed the locale to the renderer via the
889 // --lang command line flag.
890 const base::CommandLine& parsed_command_line =
891 *base::CommandLine::ForCurrentProcess();
892 const std::string& lang =
893 parsed_command_line.GetSwitchValueASCII(switches::kLang);
894 DCHECK(!lang.empty());
895 return lang;
898 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
899 return sync_message_filter();
902 scoped_refptr<base::MessageLoopProxy>
903 RenderThreadImpl::GetIOMessageLoopProxy() {
904 return ChildProcess::current()->io_message_loop_proxy();
907 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
908 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
909 PendingRenderFrameConnectMap::iterator it =
910 pending_render_frame_connects_.find(routing_id);
911 if (it == pending_render_frame_connects_.end())
912 return;
914 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
915 if (!frame)
916 return;
918 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
919 mojo::InterfaceRequest<mojo::ServiceProvider> services(
920 connection->services().Pass());
921 mojo::ServiceProviderPtr exposed_services(
922 connection->exposed_services().Pass());
923 exposed_services.set_error_handler(nullptr);
924 pending_render_frame_connects_.erase(it);
926 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
929 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
930 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
933 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
934 IPC::Listener* listener) {
935 AddRoute(routing_id, listener);
936 if (devtools_agent_message_filter_.get()) {
937 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
938 routing_id);
942 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
943 RemoveRoute(routing_id);
944 if (devtools_agent_message_filter_.get()) {
945 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
946 routing_id);
950 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
951 int routing_id,
952 mojo::InterfaceRequest<mojo::ServiceProvider> services,
953 mojo::ServiceProviderPtr exposed_services) {
954 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
955 pending_render_frame_connects_.insert(std::make_pair(
956 routing_id,
957 make_scoped_refptr(new PendingRenderFrameConnect(
958 routing_id, services.Pass(), exposed_services.Pass()))));
959 CHECK(result.second) << "Inserting a duplicate item.";
962 int RenderThreadImpl::GenerateRoutingID() {
963 int routing_id = MSG_ROUTING_NONE;
964 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
965 return routing_id;
968 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
969 channel()->AddFilter(filter);
972 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
973 channel()->RemoveFilter(filter);
976 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
977 observers_.AddObserver(observer);
980 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
981 observers_.RemoveObserver(observer);
984 void RenderThreadImpl::SetResourceDispatcherDelegate(
985 ResourceDispatcherDelegate* delegate) {
986 resource_dispatcher()->set_delegate(delegate);
989 void RenderThreadImpl::SetResourceDispatchTaskQueue(
990 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
991 // Add a filter that forces resource messages to be dispatched via a
992 // particular task runner.
993 resource_scheduling_filter_ =
994 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
995 channel()->AddFilter(resource_scheduling_filter_.get());
997 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
998 // same queue to ensure tasks are executed in the expected order.
999 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1000 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1003 void RenderThreadImpl::EnsureWebKitInitialized() {
1004 if (blink_platform_impl_)
1005 return;
1007 const base::CommandLine& command_line =
1008 *base::CommandLine::ForCurrentProcess();
1010 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1011 if (command_line.HasSwitch(switches::kEnableVtune))
1012 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1013 #endif
1015 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1017 blink_platform_impl_.reset(
1018 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1019 blink::initialize(blink_platform_impl_.get());
1021 v8::Isolate* isolate = blink::mainThreadIsolate();
1022 isolate->SetCreateHistogramFunction(CreateHistogram);
1023 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1025 main_thread_compositor_task_runner_ =
1026 renderer_scheduler_->CompositorTaskRunner();
1028 main_input_callback_.Reset(
1029 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1030 base::Unretained(this)));
1032 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1034 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1035 if (enable) {
1036 #if defined(OS_ANDROID)
1037 if (SynchronousCompositorFactory* factory =
1038 SynchronousCompositorFactory::GetInstance())
1039 compositor_message_loop_proxy_ =
1040 factory->GetCompositorMessageLoop();
1041 #endif
1042 if (!compositor_message_loop_proxy_.get()) {
1043 compositor_thread_.reset(new base::Thread("Compositor"));
1044 compositor_thread_->Start();
1045 #if defined(OS_ANDROID)
1046 compositor_thread_->SetPriority(base::ThreadPriority::DISPLAY);
1047 #endif
1048 compositor_message_loop_proxy_ =
1049 compositor_thread_->message_loop_proxy();
1050 compositor_message_loop_proxy_->PostTask(
1051 FROM_HERE,
1052 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1053 false));
1056 InputHandlerManagerClient* input_handler_manager_client = NULL;
1057 #if defined(OS_ANDROID)
1058 if (SynchronousCompositorFactory* factory =
1059 SynchronousCompositorFactory::GetInstance()) {
1060 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1062 #endif
1063 if (!input_handler_manager_client) {
1064 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1065 new InputEventFilter(main_input_callback_.callback(),
1066 main_thread_compositor_task_runner_,
1067 compositor_message_loop_proxy_));
1068 input_handler_manager_client = compositor_input_event_filter.get();
1069 input_event_filter_ = compositor_input_event_filter;
1071 input_handler_manager_.reset(new InputHandlerManager(
1072 compositor_message_loop_proxy_, input_handler_manager_client,
1073 renderer_scheduler_.get()));
1076 if (!input_event_filter_.get()) {
1077 // Always provide an input event filter implementation to ensure consistent
1078 // input event scheduling and prioritization.
1079 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1080 // MainThreadInputEventFilter, crbug.com/436057.
1081 input_event_filter_ = new MainThreadInputEventFilter(
1082 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1084 AddFilter(input_event_filter_.get());
1086 scoped_refptr<base::MessageLoopProxy> compositor_impl_side_loop;
1087 if (enable)
1088 compositor_impl_side_loop = compositor_message_loop_proxy_;
1089 else
1090 compositor_impl_side_loop = base::MessageLoopProxy::current();
1092 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1093 compositor_impl_side_loop.get());
1094 AddFilter(compositor_message_filter_.get());
1096 RenderThreadImpl::RegisterSchemes();
1098 EnableBlinkPlatformLogChannels(
1099 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1101 if (!media::IsMediaLibraryInitialized()) {
1102 WebRuntimeFeatures::enableWebAudio(false);
1105 RenderMediaClient::Initialize();
1107 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1109 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1110 AddFilter(devtools_agent_message_filter_.get());
1112 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1114 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1115 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1117 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1119 // Limit use of the scaled image cache to when deferred image decoding is
1120 // enabled.
1121 if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
1122 !is_impl_side_painting_enabled_)
1123 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1125 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1126 kImageCacheSingleAllocationByteLimit);
1128 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1129 memory_observer_.reset(new MemoryObserver());
1130 message_loop()->AddTaskObserver(memory_observer_.get());
1133 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1134 std::string allowed_ports =
1135 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1136 net::SetExplicitlyAllowedPorts(allowed_ports);
1140 void RenderThreadImpl::RegisterSchemes() {
1141 // swappedout: pages should not be accessible, and should also
1142 // be treated as empty documents that can commit synchronously.
1143 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1144 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1145 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1148 void RenderThreadImpl::NotifyTimezoneChange() {
1149 NotifyTimezoneChangeOnThisThread();
1150 RenderThread::Get()->PostTaskToAllWebWorkers(
1151 base::Bind(&NotifyTimezoneChangeOnThisThread));
1154 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1155 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1158 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1159 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1162 scoped_ptr<base::SharedMemory>
1163 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1164 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1167 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1168 return shared_bitmap_manager();
1171 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1172 WebScriptController::registerExtension(extension);
1175 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1176 idle_notification_delay_in_ms_ = initial_delay_ms;
1177 idle_timer_.Stop();
1178 idle_timer_.Start(FROM_HERE,
1179 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1180 this, &RenderThreadImpl::IdleHandler);
1183 void RenderThreadImpl::IdleHandler() {
1184 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1185 GetContentClient()->renderer()->
1186 RunIdleHandlerWhenWidgetsHidden();
1187 if (run_in_foreground_tab) {
1188 if (idle_notifications_to_skip_ > 0) {
1189 --idle_notifications_to_skip_;
1190 } else {
1191 base::allocator::ReleaseFreeMemory();
1192 discardable_shared_memory_manager()->ReleaseFreeMemory();
1194 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1195 return;
1198 base::allocator::ReleaseFreeMemory();
1199 discardable_shared_memory_manager()->ReleaseFreeMemory();
1201 // Continue the idle timer if the webkit shared timer is not suspended or
1202 // something is left to do.
1203 bool continue_timer = !webkit_shared_timer_suspended_;
1205 if (blink::mainThreadIsolate() &&
1206 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1207 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1208 continue_timer = true;
1211 // Schedule next invocation. When the tab is originally hidden, an invocation
1212 // is scheduled for kInitialIdleHandlerDelayMs in
1213 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1214 // After that, idle calls can be much less frequent, so run at a maximum of
1215 // once every kLongIdleHandlerDelayMs.
1216 // Dampen the delay using the algorithm (if delay is in seconds):
1217 // delay = delay + 1 / (delay + 2)
1218 // Using floor(delay) has a dampening effect such as:
1219 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1220 // If the delay is in milliseconds, the above formula is equivalent to:
1221 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1222 // which is equivalent to
1223 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1224 if (continue_timer) {
1225 ScheduleIdleHandler(
1226 std::max(kLongIdleHandlerDelayMs,
1227 idle_notification_delay_in_ms_ +
1228 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1230 } else {
1231 idle_timer_.Stop();
1234 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1237 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1238 return idle_notification_delay_in_ms_;
1241 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1242 int64 idle_notification_delay_in_ms) {
1243 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1246 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1247 child_histogram_message_filter()->SendHistograms(sequence_number);
1250 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1251 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1254 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1255 bool result = false;
1256 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1257 return result;
1260 void RenderThreadImpl::PostponeIdleNotification() {
1261 idle_notifications_to_skip_ = 2;
1264 scoped_refptr<media::GpuVideoAcceleratorFactories>
1265 RenderThreadImpl::GetGpuFactories() {
1266 DCHECK(IsMainThread());
1268 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1269 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1270 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1271 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1272 GetMediaThreadTaskRunner();
1273 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1274 if (!gpu_va_context_provider_.get() ||
1275 gpu_va_context_provider_->DestroyedOnMainThread()) {
1276 if (!gpu_channel_host.get()) {
1277 gpu_channel_host = EstablishGpuChannelSync(
1278 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1280 blink::WebGraphicsContext3D::Attributes attributes;
1281 bool lose_context_when_out_of_memory = false;
1282 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1283 make_scoped_ptr(
1284 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1285 gpu_channel_host.get(),
1286 attributes,
1287 lose_context_when_out_of_memory,
1288 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1289 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1290 NULL)),
1291 GPU_VIDEO_ACCELERATOR_CONTEXT);
1294 if (gpu_va_context_provider_.get()) {
1295 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1296 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_);
1298 return gpu_factories;
1301 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1302 RenderThreadImpl::CreateOffscreenContext3d() {
1303 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1304 bool lose_context_when_out_of_memory = true;
1306 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1307 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1308 return make_scoped_ptr(
1309 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1310 gpu_channel_host.get(),
1311 attributes,
1312 lose_context_when_out_of_memory,
1313 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1314 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1315 NULL));
1318 scoped_refptr<cc_blink::ContextProviderWebContext>
1319 RenderThreadImpl::SharedMainThreadContextProvider() {
1320 DCHECK(IsMainThread());
1321 if (!shared_main_thread_contexts_.get() ||
1322 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1323 shared_main_thread_contexts_ = NULL;
1324 #if defined(OS_ANDROID)
1325 if (SynchronousCompositorFactory* factory =
1326 SynchronousCompositorFactory::GetInstance()) {
1327 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1328 GetOffscreenAttribs(), "Offscreen-MainThread");
1330 #endif
1331 if (!shared_main_thread_contexts_.get()) {
1332 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1333 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT);
1335 if (shared_main_thread_contexts_.get() &&
1336 !shared_main_thread_contexts_->BindToCurrentThread())
1337 shared_main_thread_contexts_ = NULL;
1339 return shared_main_thread_contexts_;
1342 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1343 if (!audio_renderer_mixer_manager_) {
1344 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1345 GetAudioHardwareConfig()));
1348 return audio_renderer_mixer_manager_.get();
1351 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1352 if (!audio_hardware_config_) {
1353 media::AudioParameters input_params;
1354 media::AudioParameters output_params;
1355 Send(new ViewHostMsg_GetAudioHardwareConfig(
1356 &input_params, &output_params));
1358 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1359 input_params, output_params));
1362 return audio_hardware_config_.get();
1365 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1366 return ChildProcess::current()->GetShutDownEvent();
1369 #if defined(OS_WIN)
1370 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1371 const base::string16& str) {
1372 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1375 #endif // OS_WIN
1377 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1378 return service_registry();
1381 bool RenderThreadImpl::IsImplSidePaintingEnabled() {
1382 return is_impl_side_painting_enabled_;
1385 bool RenderThreadImpl::IsGpuRasterizationForced() {
1386 return is_gpu_rasterization_forced_;
1389 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1390 return is_gpu_rasterization_enabled_;
1393 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1394 return gpu_rasterization_msaa_sample_count_;
1397 bool RenderThreadImpl::IsLcdTextEnabled() {
1398 return is_lcd_text_enabled_;
1401 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1402 return is_distance_field_text_enabled_;
1405 bool RenderThreadImpl::IsZeroCopyEnabled() {
1406 return is_zero_copy_enabled_;
1409 bool RenderThreadImpl::IsOneCopyEnabled() {
1410 return is_one_copy_enabled_;
1413 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1414 return is_elastic_overscroll_enabled_;
1417 bool RenderThreadImpl::UseSingleThreadScheduler() {
1418 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
1419 return !cmd->HasSwitch(switches::kDisableSingleThreadProxyScheduler);
1422 uint32 RenderThreadImpl::GetImageTextureTarget() {
1423 return use_image_texture_target_;
1426 scoped_refptr<base::SingleThreadTaskRunner>
1427 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1428 return main_thread_compositor_task_runner_;
1431 scoped_refptr<base::SingleThreadTaskRunner>
1432 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1433 return compositor_message_loop_proxy_;
1436 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1437 return gpu_memory_buffer_manager();
1440 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1441 return renderer_scheduler_.get();
1444 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1445 return SharedMainThreadContextProvider().get();
1448 scoped_ptr<cc::BeginFrameSource>
1449 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1450 #if defined(OS_ANDROID)
1451 if (SynchronousCompositorFactory* factory =
1452 SynchronousCompositorFactory::GetInstance()) {
1453 return factory->CreateExternalBeginFrameSource(routing_id);
1455 #endif
1456 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1457 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1460 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1461 return compositor_task_graph_runner_.get();
1464 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1465 return is_gather_pixel_refs_enabled_;
1468 bool RenderThreadImpl::IsMainThread() {
1469 return !!current();
1472 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1473 return io_message_loop_proxy_;
1476 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1477 size_t size) {
1478 return scoped_ptr<base::SharedMemory>(
1479 HostAllocateSharedMemoryBuffer(size));
1482 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1483 int32 surface_id,
1484 const GPUCreateCommandBufferConfig& init_params,
1485 int32 route_id) {
1486 TRACE_EVENT1("gpu",
1487 "RenderThreadImpl::CreateViewCommandBuffer",
1488 "surface_id",
1489 surface_id);
1491 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1492 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1493 surface_id,
1494 init_params,
1495 route_id,
1496 &result);
1498 // Allow calling this from the compositor thread.
1499 thread_safe_sender()->Send(message);
1501 return result;
1504 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1505 notify_webkit_of_modal_loop_ = false;
1508 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1509 ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1510 RenderProcessObserver* observer;
1511 while ((observer = it.GetNext()) != NULL) {
1512 if (observer->OnControlMessageReceived(msg))
1513 return true;
1516 // Some messages are handled by delegates.
1517 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1518 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1519 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1520 return true;
1523 bool handled = true;
1524 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1525 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1526 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1527 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1528 OnSetZoomLevelForCurrentURL)
1529 // TODO(port): removed from render_messages_internal.h;
1530 // is there a new non-windows message I should add here?
1531 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1532 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1533 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1534 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1535 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1536 #if defined(OS_ANDROID)
1537 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1538 OnSetWebKitSharedTimersSuspended)
1539 #endif
1540 #if defined(OS_MACOSX)
1541 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1542 #endif
1543 #if defined(ENABLE_PLUGINS)
1544 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1545 #endif
1546 IPC_MESSAGE_UNHANDLED(handled = false)
1547 IPC_END_MESSAGE_MAP()
1548 return handled;
1551 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params) {
1552 CompositorDependencies* compositor_deps = this;
1553 RenderFrameImpl::CreateFrame(
1554 params.routing_id, params.parent_routing_id,
1555 params.previous_sibling_routing_id, params.proxy_routing_id,
1556 params.replication_state, compositor_deps, params.widget_params);
1559 void RenderThreadImpl::OnCreateNewFrameProxy(
1560 int routing_id,
1561 int parent_routing_id,
1562 int render_view_routing_id,
1563 const FrameReplicationState& replicated_state) {
1564 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1565 render_view_routing_id, replicated_state);
1568 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1569 const std::string& host,
1570 double zoom_level) {
1571 RenderViewZoomer zoomer(scheme, host, zoom_level);
1572 RenderView::ForEach(&zoomer);
1575 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1576 EnsureWebKitInitialized();
1577 CompositorDependencies* compositor_deps = this;
1578 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1579 RenderViewImpl::Create(params, compositor_deps, false);
1582 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1583 CauseForGpuLaunch cause_for_gpu_launch) {
1584 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1586 if (gpu_channel_.get()) {
1587 // Do nothing if we already have a GPU channel or are already
1588 // establishing one.
1589 if (!gpu_channel_->IsLost())
1590 return gpu_channel_.get();
1592 // Recreate the channel if it has been lost.
1593 gpu_channel_->DestroyChannel();
1594 gpu_channel_ = NULL;
1597 // Ask the browser for the channel name.
1598 int client_id = 0;
1599 IPC::ChannelHandle channel_handle;
1600 gpu::GPUInfo gpu_info;
1601 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1602 &client_id,
1603 &channel_handle,
1604 &gpu_info)) ||
1605 #if defined(OS_POSIX)
1606 channel_handle.socket.fd == -1 ||
1607 #endif
1608 channel_handle.name.empty()) {
1609 // Otherwise cancel the connection.
1610 return NULL;
1613 GetContentClient()->SetGpuInfo(gpu_info);
1615 // Cache some variables that are needed on the compositor thread for our
1616 // implementation of GpuChannelHostFactory.
1617 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1619 gpu_channel_ =
1620 GpuChannelHost::Create(this,
1621 gpu_info,
1622 channel_handle,
1623 ChildProcess::current()->GetShutDownEvent(),
1624 gpu_memory_buffer_manager());
1625 return gpu_channel_.get();
1628 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1629 blink::WebMediaStreamCenterClient* client) {
1630 #if defined(OS_ANDROID)
1631 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1632 switches::kDisableWebRTC))
1633 return NULL;
1634 #endif
1636 #if defined(ENABLE_WEBRTC)
1637 if (!media_stream_center_) {
1638 media_stream_center_ = GetContentClient()->renderer()
1639 ->OverrideCreateWebMediaStreamCenter(client);
1640 if (!media_stream_center_) {
1641 scoped_ptr<MediaStreamCenter> media_stream_center(
1642 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1643 media_stream_center_ = media_stream_center.release();
1646 #endif
1647 return media_stream_center_;
1650 #if defined(ENABLE_WEBRTC)
1651 PeerConnectionDependencyFactory*
1652 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1653 return peer_connection_factory_.get();
1655 #endif
1657 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1658 if (!gpu_channel_.get())
1659 return NULL;
1661 if (gpu_channel_->IsLost())
1662 return NULL;
1664 return gpu_channel_.get();
1667 #if defined(ENABLE_PLUGINS)
1668 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1669 EnsureWebKitInitialized();
1670 // The call below will cause a GetPlugins call with refresh=true, but at this
1671 // point we already know that the browser has refreshed its list, so disable
1672 // refresh temporarily to prevent each renderer process causing the list to be
1673 // regenerated.
1674 blink_platform_impl_->set_plugin_refresh_allowed(false);
1675 blink::resetPluginCache(reload_pages);
1676 blink_platform_impl_->set_plugin_refresh_allowed(true);
1678 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1680 #endif
1682 void RenderThreadImpl::OnNetworkTypeChanged(
1683 net::NetworkChangeNotifier::ConnectionType type) {
1684 EnsureWebKitInitialized();
1685 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1686 WebNetworkStateNotifier::setOnLine(online);
1687 FOR_EACH_OBSERVER(
1688 RenderProcessObserver, observers_, NetworkStateChanged(online));
1689 WebNetworkStateNotifier::setWebConnectionType(
1690 NetConnectionTypeToWebConnectionType(type));
1693 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1694 GetContentClient()->SetActiveURL(data);
1695 CHECK(false);
1698 void RenderThreadImpl::OnUpdateTimezone(const std::string& zone_id) {
1699 if (!blink_platform_impl_)
1700 return;
1701 if (!zone_id.empty()) {
1702 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
1703 icu::UnicodeString::fromUTF8(zone_id));
1704 icu::TimeZone::adoptDefault(new_zone);
1705 VLOG(1) << "ICU default timezone is set to " << zone_id;
1707 NotifyTimezoneChange();
1710 #if defined(OS_ANDROID)
1711 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1712 EnsureWebKitInitialized();
1713 // TODO(alexclarke): Remove the shared timer.
1714 if (suspend) {
1715 blink_platform_impl_->SuspendSharedTimer();
1716 renderer_scheduler_->SuspendTimerQueue();
1717 } else {
1718 blink_platform_impl_->ResumeSharedTimer();
1719 renderer_scheduler_->ResumeTimerQueue();
1721 webkit_shared_timer_suspended_ = suspend;
1723 #endif
1725 #if defined(OS_MACOSX)
1726 void RenderThreadImpl::OnUpdateScrollbarTheme(
1727 float initial_button_delay,
1728 float autoscroll_button_delay,
1729 bool jump_on_track_click,
1730 blink::ScrollerStyle preferred_scroller_style,
1731 bool redraw) {
1732 EnsureWebKitInitialized();
1733 static_cast<WebScrollbarBehaviorImpl*>(
1734 blink_platform_impl_->scrollbarBehavior())
1735 ->set_jump_on_track_click(jump_on_track_click);
1736 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1737 autoscroll_button_delay,
1738 preferred_scroller_style,
1739 redraw);
1741 #endif
1743 void RenderThreadImpl::OnCreateNewSharedWorker(
1744 const WorkerProcessMsg_CreateWorker_Params& params) {
1745 // EmbeddedSharedWorkerStub will self-destruct.
1746 new EmbeddedSharedWorkerStub(params.url,
1747 params.name,
1748 params.content_security_policy,
1749 params.security_policy_type,
1750 params.pause_on_start,
1751 params.route_id);
1754 void RenderThreadImpl::OnMemoryPressure(
1755 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1756 base::allocator::ReleaseFreeMemory();
1757 discardable_shared_memory_manager()->ReleaseFreeMemory();
1759 // Do not call into blink if it is not initialized.
1760 if (blink_platform_impl_) {
1761 blink::WebCache::pruneAll();
1763 if (blink::mainThreadIsolate()) {
1764 // Trigger full v8 garbage collection on memory pressure notifications.
1765 // This will potentially hang the renderer for a long time, however, when
1766 // we receive a memory pressure notification, we might be about to be
1767 // killed.
1768 blink::mainThreadIsolate()->LowMemoryNotification();
1769 RenderThread::Get()->PostTaskToAllWebWorkers(
1770 base::Bind(&LowMemoryNotificationOnThisThread));
1773 if (memory_pressure_level ==
1774 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1775 // Clear the image cache.
1776 blink::WebImageCache::clear();
1778 // Purge Skia font cache, by setting it to 0 and then again to the
1779 // previous limit.
1780 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1781 SkGraphics::SetFontCacheLimit(font_cache_limit);
1786 scoped_refptr<base::MessageLoopProxy>
1787 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1788 DCHECK(message_loop() == base::MessageLoop::current());
1789 if (!file_thread_) {
1790 file_thread_.reset(new base::Thread("Renderer::FILE"));
1791 file_thread_->Start();
1793 return file_thread_->message_loop_proxy();
1796 scoped_refptr<base::SingleThreadTaskRunner>
1797 RenderThreadImpl::GetMediaThreadTaskRunner() {
1798 DCHECK(message_loop() == base::MessageLoop::current());
1799 if (!media_thread_) {
1800 media_thread_.reset(new base::Thread("Media"));
1801 media_thread_->Start();
1803 #if defined(OS_ANDROID)
1804 renderer_demuxer_ = new RendererDemuxerAndroid();
1805 AddFilter(renderer_demuxer_.get());
1806 #endif
1808 return media_thread_->message_loop_proxy();
1811 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1812 blink_platform_impl_->sampleGamepads(*data);
1815 bool RenderThreadImpl::RendererIsHidden() const {
1816 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1819 void RenderThreadImpl::WidgetCreated() {
1820 bool renderer_was_hidden = RendererIsHidden();
1821 widget_count_++;
1822 if (renderer_was_hidden)
1823 OnRendererVisible();
1826 void RenderThreadImpl::WidgetDestroyed() {
1827 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1828 // unhidden before WidgetDestroyed is called.
1829 DCHECK_GT(widget_count_, 0);
1830 DCHECK_GT(widget_count_, hidden_widget_count_);
1831 widget_count_--;
1832 if (RendererIsHidden())
1833 OnRendererHidden();
1836 void RenderThreadImpl::WidgetHidden() {
1837 DCHECK_LT(hidden_widget_count_, widget_count_);
1838 hidden_widget_count_++;
1839 if (RendererIsHidden())
1840 OnRendererHidden();
1843 void RenderThreadImpl::WidgetRestored() {
1844 bool renderer_was_hidden = RendererIsHidden();
1845 DCHECK_GT(hidden_widget_count_, 0);
1846 hidden_widget_count_--;
1847 if (renderer_was_hidden)
1848 OnRendererVisible();
1851 void RenderThreadImpl::OnRendererHidden() {
1852 renderer_scheduler_->OnRendererHidden();
1854 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1855 // scheduled by the RendererScheduler - http://crbug.com/469210.
1856 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1857 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1860 void RenderThreadImpl::OnRendererVisible() {
1861 renderer_scheduler_->OnRendererVisible();
1863 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1864 return;
1866 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1869 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1870 int routing_id,
1871 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1872 mojo::ServiceProviderPtr exposed_services)
1873 : routing_id_(routing_id),
1874 services_(services.Pass()),
1875 exposed_services_(exposed_services.Pass()) {
1876 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1877 // is received. In that case, the RenderFrameHost should close the connection,
1878 // which is detected by setting an error handler on |exposed_services_|.
1879 exposed_services_.set_error_handler(this);
1882 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1885 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1886 size_t erased =
1887 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1888 routing_id_);
1889 DCHECK_EQ(1u, erased);
1892 } // namespace content