Don't send a SHChangeNotify for creating an app icon when creating a shortcut.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blob21d75dd99b9336d5419a3a3da580ab268b5aff97
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 "content/child/appcache/appcache_dispatcher.h"
37 #include "content/child/appcache/appcache_frontend_impl.h"
38 #include "content/child/child_discardable_shared_memory_manager.h"
39 #include "content/child/child_gpu_memory_buffer_manager.h"
40 #include "content/child/child_histogram_message_filter.h"
41 #include "content/child/child_resource_message_filter.h"
42 #include "content/child/child_shared_bitmap_manager.h"
43 #include "content/child/content_child_helpers.h"
44 #include "content/child/db_message_filter.h"
45 #include "content/child/indexed_db/indexed_db_dispatcher.h"
46 #include "content/child/indexed_db/indexed_db_message_filter.h"
47 #include "content/child/npapi/npobject_util.h"
48 #include "content/child/plugin_messages.h"
49 #include "content/child/resource_dispatcher.h"
50 #include "content/child/resource_scheduling_filter.h"
51 #include "content/child/runtime_features.h"
52 #include "content/child/thread_safe_sender.h"
53 #include "content/child/web_database_observer_impl.h"
54 #include "content/child/worker_task_runner.h"
55 #include "content/common/child_process_messages.h"
56 #include "content/common/content_constants_internal.h"
57 #include "content/common/database_messages.h"
58 #include "content/common/dom_storage/dom_storage_messages.h"
59 #include "content/common/frame_messages.h"
60 #include "content/common/gpu/client/context_provider_command_buffer.h"
61 #include "content/common/gpu/client/gpu_channel_host.h"
62 #include "content/common/gpu/gpu_messages.h"
63 #include "content/common/gpu/gpu_process_launch_causes.h"
64 #include "content/common/render_frame_setup.mojom.h"
65 #include "content/common/resource_messages.h"
66 #include "content/common/view_messages.h"
67 #include "content/common/worker_messages.h"
68 #include "content/public/common/content_constants.h"
69 #include "content/public/common/content_paths.h"
70 #include "content/public/common/content_switches.h"
71 #include "content/public/common/mojo_channel_switches.h"
72 #include "content/public/common/renderer_preferences.h"
73 #include "content/public/common/url_constants.h"
74 #include "content/public/renderer/content_renderer_client.h"
75 #include "content/public/renderer/render_process_observer.h"
76 #include "content/public/renderer/render_view_visitor.h"
77 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
78 #include "content/renderer/devtools/devtools_agent_filter.h"
79 #include "content/renderer/devtools/v8_sampling_profiler.h"
80 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
81 #include "content/renderer/dom_storage/webstoragearea_impl.h"
82 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
83 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
84 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
85 #include "content/renderer/gpu/compositor_output_surface.h"
86 #include "content/renderer/input/input_event_filter.h"
87 #include "content/renderer/input/input_handler_manager.h"
88 #include "content/renderer/input/main_thread_input_event_filter.h"
89 #include "content/renderer/media/aec_dump_message_filter.h"
90 #include "content/renderer/media/audio_input_message_filter.h"
91 #include "content/renderer/media/audio_message_filter.h"
92 #include "content/renderer/media/audio_renderer_mixer_manager.h"
93 #include "content/renderer/media/media_stream_center.h"
94 #include "content/renderer/media/midi_message_filter.h"
95 #include "content/renderer/media/render_media_client.h"
96 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
97 #include "content/renderer/media/video_capture_impl_manager.h"
98 #include "content/renderer/media/video_capture_message_filter.h"
99 #include "content/renderer/net_info_helper.h"
100 #include "content/renderer/p2p/socket_dispatcher.h"
101 #include "content/renderer/render_frame_proxy.h"
102 #include "content/renderer/render_process_impl.h"
103 #include "content/renderer/render_view_impl.h"
104 #include "content/renderer/renderer_blink_platform_impl.h"
105 #include "content/renderer/scheduler/renderer_scheduler.h"
106 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
107 #include "content/renderer/service_worker/cache_storage_message_filter.h"
108 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
109 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
110 #include "content/renderer/service_worker/service_worker_cache_storage_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 WebDocument document = webview->mainFrame()->document();
234 // Don't set zoom level for full-page plugin since they don't use the same
235 // zoom settings.
236 if (document.isPluginDocument())
237 return true;
238 GURL url(document.url());
239 // Empty scheme works as wildcard that matches any scheme,
240 if ((net::GetHostOrSpecFromURL(url) == host_) &&
241 (scheme_.empty() || scheme_ == url.scheme()) &&
242 !static_cast<RenderViewImpl*>(render_view)
243 ->uses_temporary_zoom_level()) {
244 webview->hidePopups();
245 webview->setZoomLevel(zoom_level_);
247 return true;
250 private:
251 const std::string scheme_;
252 const std::string host_;
253 const double zoom_level_;
255 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
258 class CompositorRasterThread : public base::SimpleThread {
259 public:
260 CompositorRasterThread(cc::TaskGraphRunner* task_graph_runner,
261 const std::string& name_prefix)
262 : base::SimpleThread(name_prefix),
263 task_graph_runner_(task_graph_runner) {}
265 // Overridden from base::SimpleThread:
266 void Run() override { task_graph_runner_->Run(); }
268 private:
269 cc::TaskGraphRunner* task_graph_runner_;
271 DISALLOW_COPY_AND_ASSIGN(CompositorRasterThread);
274 std::string HostToCustomHistogramSuffix(const std::string& host) {
275 if (host == "mail.google.com")
276 return ".gmail";
277 if (host == "docs.google.com" || host == "drive.google.com")
278 return ".docs";
279 if (host == "plus.google.com")
280 return ".plus";
281 return std::string();
284 void* CreateHistogram(
285 const char *name, int min, int max, size_t buckets) {
286 if (min <= 0)
287 min = 1;
288 std::string histogram_name;
289 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
290 if (render_thread_impl) { // Can be null in tests.
291 histogram_name = render_thread_impl->
292 histogram_customizer()->ConvertToCustomHistogramName(name);
293 } else {
294 histogram_name = std::string(name);
296 base::HistogramBase* histogram = base::Histogram::FactoryGet(
297 histogram_name, min, max, buckets,
298 base::Histogram::kUmaTargetedHistogramFlag);
299 return histogram;
302 void AddHistogramSample(void* hist, int sample) {
303 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
304 histogram->Add(sample);
307 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
308 const gfx::Size& size) {
309 return ChildThreadImpl::current()->shared_bitmap_manager()->
310 AllocateSharedBitmap(size);
313 void EnableBlinkPlatformLogChannels(const std::string& channels) {
314 if (channels.empty())
315 return;
316 base::StringTokenizer t(channels, ", ");
317 while (t.GetNext())
318 blink::enableLogChannel(t.token().c_str());
321 void NotifyTimezoneChangeOnThisThread() {
322 v8::Isolate* isolate = v8::Isolate::GetCurrent();
323 if (!isolate)
324 return;
325 v8::Date::DateTimeConfigurationChangeNotification(isolate);
328 void LowMemoryNotificationOnThisThread() {
329 v8::Isolate* isolate = v8::Isolate::GetCurrent();
330 if (!isolate)
331 return;
332 isolate->LowMemoryNotification();
335 class RenderFrameSetupImpl : public mojo::InterfaceImpl<RenderFrameSetup> {
336 public:
337 RenderFrameSetupImpl()
338 : routing_id_highmark_(-1) {
341 void ExchangeServiceProviders(
342 int32_t frame_routing_id,
343 mojo::InterfaceRequest<mojo::ServiceProvider> services,
344 mojo::ServiceProviderPtr exposed_services)
345 override {
346 // TODO(morrita): This is for investigating http://crbug.com/415059 and
347 // should be removed once it is fixed.
348 CHECK_LT(routing_id_highmark_, frame_routing_id);
349 routing_id_highmark_ = frame_routing_id;
351 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
352 // We can receive a GetServiceProviderForFrame message for a frame not yet
353 // created due to a race between the message and a ViewMsg_New IPC that
354 // triggers creation of the RenderFrame we want.
355 if (!frame) {
356 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
357 frame_routing_id, services.Pass(), exposed_services.Pass());
358 return;
361 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
364 private:
365 int32_t routing_id_highmark_;
368 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
369 mojo::BindToRequest(new RenderFrameSetupImpl(), &request);
372 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
373 blink::WebGraphicsContext3D::Attributes attributes;
374 attributes.shareResources = true;
375 attributes.depth = false;
376 attributes.stencil = false;
377 attributes.antialias = false;
378 attributes.noAutomaticFlushes = true;
379 return attributes;
382 } // namespace
384 // For measuring memory usage after each task. Behind a command line flag.
385 class MemoryObserver : public base::MessageLoop::TaskObserver {
386 public:
387 MemoryObserver() {}
388 ~MemoryObserver() override {}
390 void WillProcessTask(const base::PendingTask& pending_task) override {}
392 void DidProcessTask(const base::PendingTask& pending_task) override {
393 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
396 private:
397 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
400 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
401 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
402 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
403 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
406 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
408 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
409 const std::string& host, size_t view_count) {
410 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
411 switches::kDisableHistogramCustomizer)) {
412 return;
414 // Check if all RenderViews are displaying a page from the same host. If there
415 // is only one RenderView, the common host is this view's host. If there are
416 // many, check if this one shares the common host of the other
417 // RenderViews. It's ok to not detect some cases where the RenderViews share a
418 // common host. This information is only used for producing custom histograms.
419 if (view_count == 1)
420 SetCommonHost(host);
421 else if (host != common_host_)
422 SetCommonHost(std::string());
425 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
426 const char* histogram_name) const {
427 std::string name(histogram_name);
428 if (!common_host_histogram_suffix_.empty() &&
429 custom_histograms_.find(name) != custom_histograms_.end())
430 name += common_host_histogram_suffix_;
431 return name;
434 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
435 const std::string& host) {
436 if (host != common_host_) {
437 common_host_ = host;
438 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
439 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
443 RenderThreadImpl* RenderThreadImpl::current() {
444 return lazy_tls.Pointer()->Get();
447 RenderThreadImpl::RenderThreadImpl(const InProcessChildThreadParams& params)
448 : ChildThreadImpl(Options::Builder()
449 .InBrowserProcess(params)
450 .UseMojoChannel(ShouldUseMojoChannel())
451 .Build()) {
452 Init();
455 // When we run plugins in process, we actually run them on the render thread,
456 // which means that we need to make the render thread pump UI events.
457 RenderThreadImpl::RenderThreadImpl(
458 scoped_ptr<base::MessageLoop> main_message_loop)
459 : ChildThreadImpl(Options::Builder()
460 .UseMojoChannel(ShouldUseMojoChannel())
461 .Build()),
462 main_message_loop_(main_message_loop.Pass()) {
463 Init();
466 void RenderThreadImpl::Init() {
467 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
469 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
470 base::PlatformThread::CurrentId(),
471 kTraceEventRendererMainThreadSortIndex);
473 #if defined(OS_MACOSX) || defined(OS_ANDROID)
474 // On Mac and Android, the select popups are rendered by the browser.
475 blink::WebView::setUseExternalPopupMenus(true);
476 #endif
478 lazy_tls.Pointer()->Set(this);
480 // Register this object as the main thread.
481 ChildProcess::current()->set_main_thread(this);
483 // In single process the single process is all there is.
484 suspend_webkit_shared_timer_ = true;
485 notify_webkit_of_modal_loop_ = true;
486 webkit_shared_timer_suspended_ = false;
487 widget_count_ = 0;
488 hidden_widget_count_ = 0;
489 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
490 idle_notifications_to_skip_ = 0;
491 layout_test_mode_ = false;
493 appcache_dispatcher_.reset(
494 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
495 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
496 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
497 thread_safe_sender()));
498 renderer_scheduler_ = RendererScheduler::Create();
499 channel()->SetListenerTaskRunner(renderer_scheduler_->DefaultTaskRunner());
500 main_thread_cache_storage_dispatcher_.reset(
501 new ServiceWorkerCacheStorageDispatcher(thread_safe_sender()));
502 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
504 // Note: This may reorder messages from the ResourceDispatcher with respect to
505 // other subsystems.
506 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
507 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
508 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
509 kMaxResourceRequestsPerFlushWhenThrottled));
510 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
512 media_stream_center_ = NULL;
514 db_message_filter_ = new DBMessageFilter();
515 AddFilter(db_message_filter_.get());
517 vc_manager_.reset(new VideoCaptureImplManager());
518 AddFilter(vc_manager_->video_capture_message_filter());
520 browser_plugin_manager_.reset(new BrowserPluginManager());
521 AddObserver(browser_plugin_manager_.get());
523 #if defined(ENABLE_WEBRTC)
524 peer_connection_tracker_.reset(new PeerConnectionTracker());
525 AddObserver(peer_connection_tracker_.get());
527 p2p_socket_dispatcher_ =
528 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
529 AddFilter(p2p_socket_dispatcher_.get());
531 webrtc_identity_service_.reset(new WebRTCIdentityService());
533 aec_dump_message_filter_ =
534 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
535 message_loop()->message_loop_proxy());
536 AddFilter(aec_dump_message_filter_.get());
538 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
539 p2p_socket_dispatcher_.get()));
540 #endif // defined(ENABLE_WEBRTC)
542 audio_input_message_filter_ =
543 new AudioInputMessageFilter(GetIOMessageLoopProxy());
544 AddFilter(audio_input_message_filter_.get());
546 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
547 AddFilter(audio_message_filter_.get());
549 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
550 AddFilter(midi_message_filter_.get());
552 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
554 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
556 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
558 GetContentClient()->renderer()->RenderThreadStarted();
560 InitSkiaEventTracer();
562 const base::CommandLine& command_line =
563 *base::CommandLine::ForCurrentProcess();
565 is_impl_side_painting_enabled_ =
566 !command_line.HasSwitch(switches::kDisableImplSidePainting);
567 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
568 is_impl_side_painting_enabled_);
570 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
571 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
573 #if defined(OS_MACOSX) && !defined(OS_IOS)
574 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
575 if (is_elastic_overscroll_enabled_) {
576 base::ScopedCFTypeRef<CFStringRef> key(
577 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
578 Boolean key_exists = false;
579 Boolean value = CFPreferencesGetAppBooleanValue(
580 key, kCFPreferencesCurrentApplication, &key_exists);
581 if (key_exists && !value)
582 is_elastic_overscroll_enabled_ = false;
584 #else
585 is_elastic_overscroll_enabled_ = false;
586 #endif
588 std::string image_texture_target_string =
589 command_line.GetSwitchValueASCII(switches::kUseImageTextureTarget);
590 bool parsed_image_texture_target = base::StringToUint(
591 image_texture_target_string, &use_image_texture_target_);
592 DCHECK(parsed_image_texture_target);
594 if (command_line.HasSwitch(switches::kDisableLCDText)) {
595 is_lcd_text_enabled_ = false;
596 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
597 is_lcd_text_enabled_ = true;
598 } else {
599 #if defined(OS_ANDROID)
600 is_lcd_text_enabled_ = false;
601 #else
602 is_lcd_text_enabled_ = true;
603 #endif
606 is_gpu_rasterization_enabled_ =
607 command_line.HasSwitch(switches::kEnableGpuRasterization);
608 is_gpu_rasterization_forced_ =
609 command_line.HasSwitch(switches::kForceGpuRasterization);
611 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
612 std::string string_value = command_line.GetSwitchValueASCII(
613 switches::kGpuRasterizationMSAASampleCount);
614 bool parsed_msaa_sample_count =
615 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
616 DCHECK(parsed_msaa_sample_count) << string_value;
617 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
618 } else {
619 gpu_rasterization_msaa_sample_count_ = 0;
621 is_threaded_gpu_rasterization_enabled_ =
622 command_line.HasSwitch(switches::kEnableThreadedGpuRasterization);
624 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
625 is_distance_field_text_enabled_ = false;
626 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
627 is_distance_field_text_enabled_ = true;
628 } else {
629 #if defined(OS_ANDROID)
630 is_distance_field_text_enabled_ = true;
631 #else
632 is_distance_field_text_enabled_ = false;
633 #endif
636 // Note that under Linux, the media library will normally already have
637 // been initialized by the Zygote before this instance became a Renderer.
638 base::FilePath media_path;
639 PathService::Get(DIR_MEDIA_LIBS, &media_path);
640 if (!media_path.empty())
641 media::InitializeMediaLibrary(media_path);
643 memory_pressure_listener_.reset(new base::MemoryPressureListener(
644 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
646 compositor_task_graph_runner_.reset(new cc::TaskGraphRunner);
648 is_gather_pixel_refs_enabled_ = false;
650 if (is_impl_side_painting_enabled_) {
651 int num_raster_threads = 0;
652 std::string string_value =
653 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
654 bool parsed_num_raster_threads =
655 base::StringToInt(string_value, &num_raster_threads);
656 DCHECK(parsed_num_raster_threads) << string_value;
657 DCHECK_GT(num_raster_threads, 0);
659 // Note: Currently, gathering of pixel refs when using a single
660 // raster thread doesn't provide any benefit. This might change
661 // in the future but we avoid it for now to reduce the cost of
662 // Picture::Create.
663 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
665 while (compositor_raster_threads_.size() <
666 static_cast<size_t>(num_raster_threads)) {
667 scoped_ptr<CompositorRasterThread> raster_thread(
668 new CompositorRasterThread(
669 compositor_task_graph_runner_.get(),
670 base::StringPrintf(
671 "CompositorTileWorker%u",
672 static_cast<unsigned>(compositor_raster_threads_.size() + 1))
673 .c_str()));
674 raster_thread->Start();
675 #if defined(OS_ANDROID) || defined(OS_LINUX)
676 if (!command_line.HasSwitch(
677 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
678 raster_thread->SetThreadPriority(base::kThreadPriority_Background);
680 #endif
681 compositor_raster_threads_.push_back(raster_thread.Pass());
685 // In single process, browser main loop set up the discardable memory
686 // allocator.
687 if (!command_line.HasSwitch(switches::kSingleProcess)) {
688 base::DiscardableMemoryAllocator::SetInstance(
689 ChildThreadImpl::discardable_shared_memory_manager());
692 service_registry()->AddService<RenderFrameSetup>(
693 base::Bind(CreateRenderFrameSetup));
695 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
698 RenderThreadImpl::~RenderThreadImpl() {
701 void RenderThreadImpl::Shutdown() {
702 FOR_EACH_OBSERVER(
703 RenderProcessObserver, observers_, OnRenderProcessShutdown());
705 ChildThreadImpl::Shutdown();
707 if (memory_observer_) {
708 message_loop()->RemoveTaskObserver(memory_observer_.get());
709 memory_observer_.reset();
712 // Wait for all databases to be closed.
713 if (blink_platform_impl_) {
714 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
715 // processing timer events while we're already in the process of shutting
716 // down blink, put a ScopePageLoadDeferrer on the stack.
717 WebView::willEnterModalLoop();
718 blink_platform_impl_->web_database_observer_impl()
719 ->WaitForAllDatabasesToClose();
720 WebView::didExitModalLoop();
723 // Shutdown in reverse of the initialization order.
724 if (devtools_agent_message_filter_.get()) {
725 RemoveFilter(devtools_agent_message_filter_.get());
726 devtools_agent_message_filter_ = NULL;
729 RemoveFilter(audio_input_message_filter_.get());
730 audio_input_message_filter_ = NULL;
732 #if defined(ENABLE_WEBRTC)
733 RTCPeerConnectionHandler::DestructAllHandlers();
734 // |peer_connection_factory_| cannot be deleted until after the main message
735 // loop has been destroyed. This is because there may be pending tasks that
736 // hold on to objects produced by the PC factory that depend on threads owned
737 // by the PC factory. Once those tasks have been freed, the factory can be
738 // deleted.
739 #endif
740 RemoveFilter(vc_manager_->video_capture_message_filter());
741 vc_manager_.reset();
743 RemoveFilter(db_message_filter_.get());
744 db_message_filter_ = NULL;
746 // Shutdown the file thread if it's running.
747 if (file_thread_)
748 file_thread_->Stop();
750 if (compositor_message_filter_.get()) {
751 RemoveFilter(compositor_message_filter_.get());
752 compositor_message_filter_ = NULL;
755 media_thread_.reset();
757 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
758 RemoveFilter(audio_message_filter_.get());
759 audio_message_filter_ = NULL;
761 compositor_thread_.reset();
763 // Shutdown raster threads.
764 compositor_task_graph_runner_->Shutdown();
765 while (!compositor_raster_threads_.empty()) {
766 compositor_raster_threads_.back()->Join();
767 compositor_raster_threads_.pop_back();
769 compositor_task_graph_runner_.reset();
771 main_input_callback_.Cancel();
772 input_handler_manager_.reset();
773 if (input_event_filter_.get()) {
774 RemoveFilter(input_event_filter_.get());
775 input_event_filter_ = NULL;
778 // RemoveEmbeddedWorkerRoute may be called while deleting
779 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
780 // RenderThreadImpl.
781 embedded_worker_dispatcher_.reset();
783 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
784 // hold pointers to V8 objects (e.g., via pending requests).
785 main_thread_indexed_db_dispatcher_.reset();
787 main_thread_compositor_task_runner_ = NULL;
789 if (gpu_channel_.get())
790 gpu_channel_->DestroyChannel();
791 gpu_va_context_provider_ = nullptr;
793 // TODO(port)
794 #if defined(OS_WIN)
795 // Clean up plugin channels before this thread goes away.
796 NPChannelBase::CleanupChannels();
797 #endif
799 // Shut down the message loop and the renderer scheduler before shutting down
800 // Blink. This prevents a scenario where a pending task in the message loop
801 // accesses Blink objects after Blink shuts down.
802 // This must be at the very end of the shutdown sequence. You must not touch
803 // the message loop after this.
804 renderer_scheduler_->Shutdown();
805 main_message_loop_.reset();
806 if (blink_platform_impl_)
807 blink::shutdown();
809 lazy_tls.Pointer()->Set(NULL);
812 bool RenderThreadImpl::Send(IPC::Message* msg) {
813 // Certain synchronous messages cannot always be processed synchronously by
814 // the browser, e.g., putting up UI and waiting for the user. This could cause
815 // a complete hang of Chrome if a windowed plugin is trying to communicate
816 // with the renderer thread since the browser's UI thread could be stuck
817 // (within a Windows API call) trying to synchronously communicate with the
818 // plugin. The remedy is to pump messages on this thread while the browser
819 // is processing this request. This creates an opportunity for re-entrancy
820 // into WebKit, so we need to take care to disable callbacks, timers, and
821 // pending network loads that could trigger such callbacks.
822 bool pumping_events = false;
823 if (msg->is_sync()) {
824 if (msg->is_caller_pumping_messages()) {
825 pumping_events = true;
829 bool suspend_webkit_shared_timer = true; // default value
830 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
832 bool notify_webkit_of_modal_loop = true; // default value
833 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
835 #if defined(ENABLE_PLUGINS)
836 int render_view_id = MSG_ROUTING_NONE;
837 #endif
839 if (pumping_events) {
840 if (suspend_webkit_shared_timer)
841 blink_platform_impl_->SuspendSharedTimer();
843 if (notify_webkit_of_modal_loop)
844 WebView::willEnterModalLoop();
845 #if defined(ENABLE_PLUGINS)
846 RenderViewImpl* render_view =
847 RenderViewImpl::FromRoutingID(msg->routing_id());
848 if (render_view) {
849 render_view_id = msg->routing_id();
850 PluginChannelHost::Broadcast(
851 new PluginMsg_SignalModalDialogEvent(render_view_id));
853 #endif
856 bool rv = ChildThreadImpl::Send(msg);
858 if (pumping_events) {
859 #if defined(ENABLE_PLUGINS)
860 if (render_view_id != MSG_ROUTING_NONE) {
861 PluginChannelHost::Broadcast(
862 new PluginMsg_ResetModalDialogEvent(render_view_id));
864 #endif
866 if (notify_webkit_of_modal_loop)
867 WebView::didExitModalLoop();
869 if (suspend_webkit_shared_timer)
870 blink_platform_impl_->ResumeSharedTimer();
873 return rv;
876 scoped_refptr<base::SingleThreadTaskRunner> RenderThreadImpl::GetTaskRunner() {
877 return GetRendererScheduler()->DefaultTaskRunner();
880 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
881 return channel();
884 std::string RenderThreadImpl::GetLocale() {
885 // The browser process should have passed the locale to the renderer via the
886 // --lang command line flag.
887 const base::CommandLine& parsed_command_line =
888 *base::CommandLine::ForCurrentProcess();
889 const std::string& lang =
890 parsed_command_line.GetSwitchValueASCII(switches::kLang);
891 DCHECK(!lang.empty());
892 return lang;
895 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
896 return sync_message_filter();
899 scoped_refptr<base::MessageLoopProxy>
900 RenderThreadImpl::GetIOMessageLoopProxy() {
901 return ChildProcess::current()->io_message_loop_proxy();
904 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
905 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
906 PendingRenderFrameConnectMap::iterator it =
907 pending_render_frame_connects_.find(routing_id);
908 if (it == pending_render_frame_connects_.end())
909 return;
911 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
912 if (!frame)
913 return;
915 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
916 mojo::InterfaceRequest<mojo::ServiceProvider> services(
917 connection->services().Pass());
918 mojo::ServiceProviderPtr exposed_services(
919 connection->exposed_services().Pass());
920 exposed_services.set_error_handler(nullptr);
921 pending_render_frame_connects_.erase(it);
923 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
926 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
927 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
930 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
931 IPC::Listener* listener) {
932 AddRoute(routing_id, listener);
933 if (devtools_agent_message_filter_.get()) {
934 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
935 routing_id);
939 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
940 RemoveRoute(routing_id);
941 if (devtools_agent_message_filter_.get()) {
942 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
943 routing_id);
947 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
948 int routing_id,
949 mojo::InterfaceRequest<mojo::ServiceProvider> services,
950 mojo::ServiceProviderPtr exposed_services) {
951 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
952 pending_render_frame_connects_.insert(std::make_pair(
953 routing_id,
954 make_scoped_refptr(new PendingRenderFrameConnect(
955 routing_id, services.Pass(), exposed_services.Pass()))));
956 CHECK(result.second) << "Inserting a duplicate item.";
959 int RenderThreadImpl::GenerateRoutingID() {
960 int routing_id = MSG_ROUTING_NONE;
961 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
962 return routing_id;
965 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
966 channel()->AddFilter(filter);
969 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
970 channel()->RemoveFilter(filter);
973 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
974 observers_.AddObserver(observer);
977 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
978 observers_.RemoveObserver(observer);
981 void RenderThreadImpl::SetResourceDispatcherDelegate(
982 ResourceDispatcherDelegate* delegate) {
983 resource_dispatcher()->set_delegate(delegate);
986 void RenderThreadImpl::SetResourceDispatchTaskQueue(
987 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
988 // Add a filter that forces resource messages to be dispatched via a
989 // particular task runner.
990 resource_scheduling_filter_ =
991 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
992 channel()->AddFilter(resource_scheduling_filter_.get());
994 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
995 // same queue to ensure tasks are executed in the expected order.
996 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
997 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1000 void RenderThreadImpl::EnsureWebKitInitialized() {
1001 if (blink_platform_impl_)
1002 return;
1004 const base::CommandLine& command_line =
1005 *base::CommandLine::ForCurrentProcess();
1007 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1008 if (command_line.HasSwitch(switches::kEnableVtune))
1009 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1010 #endif
1012 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1014 blink_platform_impl_.reset(
1015 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1016 blink::initialize(blink_platform_impl_.get());
1018 v8::Isolate* isolate = blink::mainThreadIsolate();
1019 isolate->SetCreateHistogramFunction(CreateHistogram);
1020 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1022 main_thread_compositor_task_runner_ =
1023 renderer_scheduler_->CompositorTaskRunner();
1025 main_input_callback_.Reset(
1026 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1027 base::Unretained(this)));
1029 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1031 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1032 if (enable) {
1033 #if defined(OS_ANDROID)
1034 if (SynchronousCompositorFactory* factory =
1035 SynchronousCompositorFactory::GetInstance())
1036 compositor_message_loop_proxy_ =
1037 factory->GetCompositorMessageLoop();
1038 #endif
1039 if (!compositor_message_loop_proxy_.get()) {
1040 compositor_thread_.reset(new base::Thread("Compositor"));
1041 compositor_thread_->Start();
1042 #if defined(OS_ANDROID)
1043 compositor_thread_->SetPriority(base::kThreadPriority_Display);
1044 #endif
1045 compositor_message_loop_proxy_ =
1046 compositor_thread_->message_loop_proxy();
1047 compositor_message_loop_proxy_->PostTask(
1048 FROM_HERE,
1049 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1050 false));
1053 InputHandlerManagerClient* input_handler_manager_client = NULL;
1054 #if defined(OS_ANDROID)
1055 if (SynchronousCompositorFactory* factory =
1056 SynchronousCompositorFactory::GetInstance()) {
1057 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1059 #endif
1060 if (!input_handler_manager_client) {
1061 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1062 new InputEventFilter(main_input_callback_.callback(),
1063 main_thread_compositor_task_runner_,
1064 compositor_message_loop_proxy_));
1065 input_handler_manager_client = compositor_input_event_filter.get();
1066 input_event_filter_ = compositor_input_event_filter;
1068 input_handler_manager_.reset(new InputHandlerManager(
1069 compositor_message_loop_proxy_, input_handler_manager_client,
1070 renderer_scheduler_.get()));
1073 if (!input_event_filter_.get()) {
1074 // Always provide an input event filter implementation to ensure consistent
1075 // input event scheduling and prioritization.
1076 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1077 // MainThreadInputEventFilter, crbug.com/436057.
1078 input_event_filter_ = new MainThreadInputEventFilter(
1079 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1081 AddFilter(input_event_filter_.get());
1083 scoped_refptr<base::MessageLoopProxy> compositor_impl_side_loop;
1084 if (enable)
1085 compositor_impl_side_loop = compositor_message_loop_proxy_;
1086 else
1087 compositor_impl_side_loop = base::MessageLoopProxy::current();
1089 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1090 compositor_impl_side_loop.get());
1091 AddFilter(compositor_message_filter_.get());
1093 RenderThreadImpl::RegisterSchemes();
1095 EnableBlinkPlatformLogChannels(
1096 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1098 if (!media::IsMediaLibraryInitialized()) {
1099 WebRuntimeFeatures::enableWebAudio(false);
1102 RenderMediaClient::Initialize();
1104 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1106 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1107 AddFilter(devtools_agent_message_filter_.get());
1109 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1111 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1112 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1114 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1116 // Limit use of the scaled image cache to when deferred image decoding is
1117 // enabled.
1118 if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
1119 !is_impl_side_painting_enabled_)
1120 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1122 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1123 kImageCacheSingleAllocationByteLimit);
1125 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1126 memory_observer_.reset(new MemoryObserver());
1127 message_loop()->AddTaskObserver(memory_observer_.get());
1131 void RenderThreadImpl::RegisterSchemes() {
1132 // swappedout: pages should not be accessible, and should also
1133 // be treated as empty documents that can commit synchronously.
1134 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1135 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1136 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1139 void RenderThreadImpl::NotifyTimezoneChange() {
1140 NotifyTimezoneChangeOnThisThread();
1141 RenderThread::Get()->PostTaskToAllWebWorkers(
1142 base::Bind(&NotifyTimezoneChangeOnThisThread));
1145 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1146 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1149 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1150 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1153 scoped_ptr<base::SharedMemory>
1154 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1155 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1158 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1159 return shared_bitmap_manager();
1162 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1163 WebScriptController::registerExtension(extension);
1166 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1167 idle_notification_delay_in_ms_ = initial_delay_ms;
1168 idle_timer_.Stop();
1169 idle_timer_.Start(FROM_HERE,
1170 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1171 this, &RenderThreadImpl::IdleHandler);
1174 void RenderThreadImpl::IdleHandler() {
1175 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1176 GetContentClient()->renderer()->
1177 RunIdleHandlerWhenWidgetsHidden();
1178 if (run_in_foreground_tab) {
1179 if (idle_notifications_to_skip_ > 0) {
1180 --idle_notifications_to_skip_;
1181 } else {
1182 base::allocator::ReleaseFreeMemory();
1184 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1185 return;
1188 base::allocator::ReleaseFreeMemory();
1189 discardable_shared_memory_manager()->ReleaseFreeMemory();
1191 // Continue the idle timer if the webkit shared timer is not suspended or
1192 // something is left to do.
1193 bool continue_timer = !webkit_shared_timer_suspended_;
1195 if (blink::mainThreadIsolate() &&
1196 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1197 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1198 continue_timer = true;
1201 // Schedule next invocation. When the tab is originally hidden, an invocation
1202 // is scheduled for kInitialIdleHandlerDelayMs in
1203 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1204 // After that, idle calls can be much less frequent, so run at a maximum of
1205 // once every kLongIdleHandlerDelayMs.
1206 // Dampen the delay using the algorithm (if delay is in seconds):
1207 // delay = delay + 1 / (delay + 2)
1208 // Using floor(delay) has a dampening effect such as:
1209 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1210 // If the delay is in milliseconds, the above formula is equivalent to:
1211 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1212 // which is equivalent to
1213 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1214 if (continue_timer) {
1215 ScheduleIdleHandler(
1216 std::max(kLongIdleHandlerDelayMs,
1217 idle_notification_delay_in_ms_ +
1218 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1220 } else {
1221 idle_timer_.Stop();
1224 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1227 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1228 return idle_notification_delay_in_ms_;
1231 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1232 int64 idle_notification_delay_in_ms) {
1233 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1236 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1237 child_histogram_message_filter()->SendHistograms(sequence_number);
1240 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1241 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1244 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1245 bool result = false;
1246 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1247 return result;
1250 void RenderThreadImpl::PostponeIdleNotification() {
1251 idle_notifications_to_skip_ = 2;
1254 scoped_refptr<media::GpuVideoAcceleratorFactories>
1255 RenderThreadImpl::GetGpuFactories() {
1256 DCHECK(IsMainThread());
1258 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1259 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1260 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1261 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1262 GetMediaThreadTaskRunner();
1263 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1264 if (!gpu_va_context_provider_.get() ||
1265 gpu_va_context_provider_->DestroyedOnMainThread()) {
1266 if (!gpu_channel_host.get()) {
1267 gpu_channel_host = EstablishGpuChannelSync(
1268 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1270 blink::WebGraphicsContext3D::Attributes attributes;
1271 bool lose_context_when_out_of_memory = false;
1272 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1273 make_scoped_ptr(
1274 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1275 gpu_channel_host.get(),
1276 attributes,
1277 lose_context_when_out_of_memory,
1278 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1279 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1280 NULL)),
1281 "GPU-VideoAccelerator-Offscreen");
1284 if (gpu_va_context_provider_.get()) {
1285 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1286 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_);
1288 return gpu_factories;
1291 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1292 RenderThreadImpl::CreateOffscreenContext3d() {
1293 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1294 bool lose_context_when_out_of_memory = true;
1296 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1297 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1298 return make_scoped_ptr(
1299 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1300 gpu_channel_host.get(),
1301 attributes,
1302 lose_context_when_out_of_memory,
1303 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1304 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1305 NULL));
1308 scoped_refptr<cc_blink::ContextProviderWebContext>
1309 RenderThreadImpl::SharedMainThreadContextProvider() {
1310 DCHECK(IsMainThread());
1311 if (!shared_main_thread_contexts_.get() ||
1312 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1313 shared_main_thread_contexts_ = NULL;
1314 #if defined(OS_ANDROID)
1315 if (SynchronousCompositorFactory* factory =
1316 SynchronousCompositorFactory::GetInstance()) {
1317 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1318 GetOffscreenAttribs(), "Offscreen-MainThread");
1320 #endif
1321 if (!shared_main_thread_contexts_.get()) {
1322 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1323 CreateOffscreenContext3d(), "Offscreen-MainThread");
1325 if (shared_main_thread_contexts_.get() &&
1326 !shared_main_thread_contexts_->BindToCurrentThread())
1327 shared_main_thread_contexts_ = NULL;
1329 return shared_main_thread_contexts_;
1332 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1333 if (!audio_renderer_mixer_manager_) {
1334 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1335 GetAudioHardwareConfig()));
1338 return audio_renderer_mixer_manager_.get();
1341 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1342 return &audio_hardware_config_;
1345 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1346 return ChildProcess::current()->GetShutDownEvent();
1349 #if defined(OS_WIN)
1350 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1351 const base::string16& str) {
1352 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1355 #endif // OS_WIN
1357 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1358 return service_registry();
1361 bool RenderThreadImpl::IsImplSidePaintingEnabled() {
1362 return is_impl_side_painting_enabled_;
1365 bool RenderThreadImpl::IsGpuRasterizationForced() {
1366 return is_gpu_rasterization_forced_;
1369 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1370 return is_gpu_rasterization_enabled_;
1373 bool RenderThreadImpl::IsThreadedGpuRasterizationEnabled() {
1374 return is_threaded_gpu_rasterization_enabled_;
1377 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1378 return gpu_rasterization_msaa_sample_count_;
1381 bool RenderThreadImpl::IsLcdTextEnabled() {
1382 return is_lcd_text_enabled_;
1385 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1386 return is_distance_field_text_enabled_;
1389 bool RenderThreadImpl::IsZeroCopyEnabled() {
1390 return is_zero_copy_enabled_;
1393 bool RenderThreadImpl::IsOneCopyEnabled() {
1394 return is_one_copy_enabled_;
1397 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1398 return is_elastic_overscroll_enabled_;
1401 bool RenderThreadImpl::UseSingleThreadScheduler() {
1402 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
1403 return !cmd->HasSwitch(switches::kDisableSingleThreadProxyScheduler);
1406 uint32 RenderThreadImpl::GetImageTextureTarget() {
1407 return use_image_texture_target_;
1410 scoped_refptr<base::SingleThreadTaskRunner>
1411 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1412 return main_thread_compositor_task_runner_;
1415 scoped_refptr<base::SingleThreadTaskRunner>
1416 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1417 return compositor_message_loop_proxy_;
1420 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1421 return gpu_memory_buffer_manager();
1424 RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1425 return renderer_scheduler_.get();
1428 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1429 return SharedMainThreadContextProvider().get();
1432 scoped_ptr<cc::BeginFrameSource>
1433 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1434 #if defined(OS_ANDROID)
1435 if (SynchronousCompositorFactory* factory =
1436 SynchronousCompositorFactory::GetInstance()) {
1437 return factory->CreateExternalBeginFrameSource(routing_id);
1439 #endif
1440 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1441 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1444 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1445 return compositor_task_graph_runner_.get();
1448 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1449 return is_gather_pixel_refs_enabled_;
1452 bool RenderThreadImpl::IsMainThread() {
1453 return !!current();
1456 base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1457 return message_loop();
1460 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1461 return io_message_loop_proxy_;
1464 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1465 size_t size) {
1466 return scoped_ptr<base::SharedMemory>(
1467 HostAllocateSharedMemoryBuffer(size));
1470 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1471 int32 surface_id,
1472 const GPUCreateCommandBufferConfig& init_params,
1473 int32 route_id) {
1474 TRACE_EVENT1("gpu",
1475 "RenderThreadImpl::CreateViewCommandBuffer",
1476 "surface_id",
1477 surface_id);
1479 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1480 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1481 surface_id,
1482 init_params,
1483 route_id,
1484 &result);
1486 // Allow calling this from the compositor thread.
1487 thread_safe_sender()->Send(message);
1489 return result;
1492 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1493 suspend_webkit_shared_timer_ = false;
1496 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1497 notify_webkit_of_modal_loop_ = false;
1500 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1501 ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1502 RenderProcessObserver* observer;
1503 while ((observer = it.GetNext()) != NULL) {
1504 if (observer->OnControlMessageReceived(msg))
1505 return true;
1508 // Some messages are handled by delegates.
1509 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1510 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1511 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1512 return true;
1515 bool handled = true;
1516 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1517 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1518 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1519 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1520 OnSetZoomLevelForCurrentURL)
1521 // TODO(port): removed from render_messages_internal.h;
1522 // is there a new non-windows message I should add here?
1523 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1524 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1525 IPC_MESSAGE_HANDLER(ViewMsg_SetAudioHardwareConfig,
1526 OnSetAudioHardwareConfig)
1527 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1528 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1529 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1530 #if defined(OS_ANDROID)
1531 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1532 OnSetWebKitSharedTimersSuspended)
1533 #endif
1534 #if defined(OS_MACOSX)
1535 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1536 #endif
1537 #if defined(ENABLE_PLUGINS)
1538 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1539 #endif
1540 IPC_MESSAGE_UNHANDLED(handled = false)
1541 IPC_END_MESSAGE_MAP()
1542 return handled;
1545 void RenderThreadImpl::OnCreateNewFrame(
1546 int routing_id,
1547 int parent_routing_id,
1548 int proxy_routing_id,
1549 const FrameReplicationState& replicated_state,
1550 FrameMsg_NewFrame_WidgetParams params) {
1551 CompositorDependencies* compositor_deps = this;
1552 RenderFrameImpl::CreateFrame(routing_id, parent_routing_id, proxy_routing_id,
1553 replicated_state, compositor_deps, params);
1556 void RenderThreadImpl::OnCreateNewFrameProxy(
1557 int routing_id,
1558 int parent_routing_id,
1559 int render_view_routing_id,
1560 const FrameReplicationState& replicated_state) {
1561 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1562 render_view_routing_id, replicated_state);
1565 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1566 const std::string& host,
1567 double zoom_level) {
1568 RenderViewZoomer zoomer(scheme, host, zoom_level);
1569 RenderView::ForEach(&zoomer);
1572 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1573 EnsureWebKitInitialized();
1574 CompositorDependencies* compositor_deps = this;
1575 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1576 RenderViewImpl::Create(params, compositor_deps, false);
1579 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1580 CauseForGpuLaunch cause_for_gpu_launch) {
1581 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1583 if (gpu_channel_.get()) {
1584 // Do nothing if we already have a GPU channel or are already
1585 // establishing one.
1586 if (!gpu_channel_->IsLost())
1587 return gpu_channel_.get();
1589 // Recreate the channel if it has been lost.
1590 gpu_channel_ = NULL;
1593 // Ask the browser for the channel name.
1594 int client_id = 0;
1595 IPC::ChannelHandle channel_handle;
1596 gpu::GPUInfo gpu_info;
1597 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1598 &client_id,
1599 &channel_handle,
1600 &gpu_info)) ||
1601 #if defined(OS_POSIX)
1602 channel_handle.socket.fd == -1 ||
1603 #endif
1604 channel_handle.name.empty()) {
1605 // Otherwise cancel the connection.
1606 return NULL;
1609 GetContentClient()->SetGpuInfo(gpu_info);
1611 // Cache some variables that are needed on the compositor thread for our
1612 // implementation of GpuChannelHostFactory.
1613 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1615 gpu_channel_ =
1616 GpuChannelHost::Create(this,
1617 gpu_info,
1618 channel_handle,
1619 ChildProcess::current()->GetShutDownEvent(),
1620 gpu_memory_buffer_manager());
1621 return gpu_channel_.get();
1624 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1625 blink::WebMediaStreamCenterClient* client) {
1626 #if defined(OS_ANDROID)
1627 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1628 switches::kDisableWebRTC))
1629 return NULL;
1630 #endif
1632 #if defined(ENABLE_WEBRTC)
1633 if (!media_stream_center_) {
1634 media_stream_center_ = GetContentClient()->renderer()
1635 ->OverrideCreateWebMediaStreamCenter(client);
1636 if (!media_stream_center_) {
1637 scoped_ptr<MediaStreamCenter> media_stream_center(
1638 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1639 media_stream_center_ = media_stream_center.release();
1642 #endif
1643 return media_stream_center_;
1646 #if defined(ENABLE_WEBRTC)
1647 PeerConnectionDependencyFactory*
1648 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1649 return peer_connection_factory_.get();
1651 #endif
1653 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1654 if (!gpu_channel_.get())
1655 return NULL;
1657 if (gpu_channel_->IsLost())
1658 return NULL;
1660 return gpu_channel_.get();
1663 #if defined(ENABLE_PLUGINS)
1664 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1665 EnsureWebKitInitialized();
1666 // The call below will cause a GetPlugins call with refresh=true, but at this
1667 // point we already know that the browser has refreshed its list, so disable
1668 // refresh temporarily to prevent each renderer process causing the list to be
1669 // regenerated.
1670 blink_platform_impl_->set_plugin_refresh_allowed(false);
1671 blink::resetPluginCache(reload_pages);
1672 blink_platform_impl_->set_plugin_refresh_allowed(true);
1674 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1676 #endif
1678 void RenderThreadImpl::OnNetworkTypeChanged(
1679 net::NetworkChangeNotifier::ConnectionType type) {
1680 EnsureWebKitInitialized();
1681 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1682 WebNetworkStateNotifier::setOnLine(online);
1683 FOR_EACH_OBSERVER(
1684 RenderProcessObserver, observers_, NetworkStateChanged(online));
1685 WebNetworkStateNotifier::setWebConnectionType(
1686 NetConnectionTypeToWebConnectionType(type));
1689 void RenderThreadImpl::OnSetAudioHardwareConfig(
1690 const media::AudioParameters& input,
1691 const media::AudioParameters& output) {
1692 audio_hardware_config_.UpdateInputConfig(input);
1693 audio_hardware_config_.UpdateOutputConfig(output);
1696 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1697 GetContentClient()->SetActiveURL(data);
1698 CHECK(false);
1701 void RenderThreadImpl::OnUpdateTimezone() {
1702 if (!blink_platform_impl_)
1703 return;
1704 NotifyTimezoneChange();
1707 #if defined(OS_ANDROID)
1708 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1709 if (suspend_webkit_shared_timer_) {
1710 EnsureWebKitInitialized();
1711 if (suspend) {
1712 blink_platform_impl_->SuspendSharedTimer();
1713 } else {
1714 blink_platform_impl_->ResumeSharedTimer();
1716 webkit_shared_timer_suspended_ = suspend;
1719 #endif
1721 #if defined(OS_MACOSX)
1722 void RenderThreadImpl::OnUpdateScrollbarTheme(
1723 float initial_button_delay,
1724 float autoscroll_button_delay,
1725 bool jump_on_track_click,
1726 blink::ScrollerStyle preferred_scroller_style,
1727 bool redraw) {
1728 EnsureWebKitInitialized();
1729 static_cast<WebScrollbarBehaviorImpl*>(
1730 blink_platform_impl_->scrollbarBehavior())
1731 ->set_jump_on_track_click(jump_on_track_click);
1732 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1733 autoscroll_button_delay,
1734 preferred_scroller_style,
1735 redraw);
1737 #endif
1739 void RenderThreadImpl::OnCreateNewSharedWorker(
1740 const WorkerProcessMsg_CreateWorker_Params& params) {
1741 // EmbeddedSharedWorkerStub will self-destruct.
1742 new EmbeddedSharedWorkerStub(params.url,
1743 params.name,
1744 params.content_security_policy,
1745 params.security_policy_type,
1746 params.pause_on_start,
1747 params.route_id);
1750 void RenderThreadImpl::OnMemoryPressure(
1751 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1752 base::allocator::ReleaseFreeMemory();
1754 // Do not call into blink if it is not initialized.
1755 if (blink_platform_impl_) {
1756 blink::WebCache::pruneAll();
1758 if (blink::mainThreadIsolate()) {
1759 // Trigger full v8 garbage collection on memory pressure notifications.
1760 // This will potentially hang the renderer for a long time, however, when
1761 // we receive a memory pressure notification, we might be about to be
1762 // killed.
1763 blink::mainThreadIsolate()->LowMemoryNotification();
1764 RenderThread::Get()->PostTaskToAllWebWorkers(
1765 base::Bind(&LowMemoryNotificationOnThisThread));
1768 if (memory_pressure_level ==
1769 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1770 // Clear the image cache.
1771 blink::WebImageCache::clear();
1773 // Purge Skia font cache, by setting it to 0 and then again to the
1774 // previous limit.
1775 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1776 SkGraphics::SetFontCacheLimit(font_cache_limit);
1781 scoped_refptr<base::MessageLoopProxy>
1782 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1783 DCHECK(message_loop() == base::MessageLoop::current());
1784 if (!file_thread_) {
1785 file_thread_.reset(new base::Thread("Renderer::FILE"));
1786 file_thread_->Start();
1788 return file_thread_->message_loop_proxy();
1791 scoped_refptr<base::SingleThreadTaskRunner>
1792 RenderThreadImpl::GetMediaThreadTaskRunner() {
1793 DCHECK(message_loop() == base::MessageLoop::current());
1794 if (!media_thread_) {
1795 media_thread_.reset(new base::Thread("Media"));
1796 media_thread_->Start();
1798 #if defined(OS_ANDROID)
1799 renderer_demuxer_ = new RendererDemuxerAndroid();
1800 AddFilter(renderer_demuxer_.get());
1801 #endif
1803 return media_thread_->message_loop_proxy();
1806 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1807 blink_platform_impl_->sampleGamepads(*data);
1810 void RenderThreadImpl::WidgetCreated() {
1811 widget_count_++;
1814 void RenderThreadImpl::WidgetDestroyed() {
1815 widget_count_--;
1818 void RenderThreadImpl::WidgetHidden() {
1819 DCHECK_LT(hidden_widget_count_, widget_count_);
1820 hidden_widget_count_++;
1822 if (widget_count_ && hidden_widget_count_ == widget_count_) {
1823 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1824 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1828 void RenderThreadImpl::WidgetRestored() {
1829 DCHECK_GT(hidden_widget_count_, 0);
1830 hidden_widget_count_--;
1832 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1833 return;
1836 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1839 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1840 int routing_id,
1841 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1842 mojo::ServiceProviderPtr exposed_services)
1843 : routing_id_(routing_id),
1844 services_(services.Pass()),
1845 exposed_services_(exposed_services.Pass()) {
1846 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1847 // is received. In that case, the RenderFrameHost should close the connection,
1848 // which is detected by setting an error handler on |exposed_services_|.
1849 exposed_services_.set_error_handler(this);
1852 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1855 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1856 size_t erased =
1857 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1858 routing_id_);
1859 DCHECK_EQ(1u, erased);
1862 } // namespace content