Roll src/third_party/WebKit a452221:9ff6d11 (svn 202117:202119)
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blobdb40b5af28e9f0cdee38e39c246d4d9e1ff14867
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/location.h"
16 #include "base/logging.h"
17 #include "base/memory/discardable_memory_allocator.h"
18 #include "base/memory/shared_memory.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_tokenizer.h"
26 #include "base/strings/sys_string_conversions.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/thread_task_runner_handle.h"
29 #include "base/threading/simple_thread.h"
30 #include "base/threading/thread_local.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/trace_event/memory_dump_manager.h"
33 #include "base/trace_event/trace_event.h"
34 #include "base/values.h"
35 #include "cc/base/histograms.h"
36 #include "cc/base/switches.h"
37 #include "cc/blink/web_external_bitmap_impl.h"
38 #include "cc/blink/web_layer_impl.h"
39 #include "cc/raster/task_graph_runner.h"
40 #include "cc/trees/layer_tree_settings.h"
41 #include "components/scheduler/renderer/renderer_scheduler.h"
42 #include "content/child/appcache/appcache_dispatcher.h"
43 #include "content/child/appcache/appcache_frontend_impl.h"
44 #include "content/child/child_discardable_shared_memory_manager.h"
45 #include "content/child/child_gpu_memory_buffer_manager.h"
46 #include "content/child/child_histogram_message_filter.h"
47 #include "content/child/child_resource_message_filter.h"
48 #include "content/child/child_shared_bitmap_manager.h"
49 #include "content/child/content_child_helpers.h"
50 #include "content/child/db_message_filter.h"
51 #include "content/child/indexed_db/indexed_db_dispatcher.h"
52 #include "content/child/indexed_db/indexed_db_message_filter.h"
53 #include "content/child/npapi/npobject_util.h"
54 #include "content/child/plugin_messages.h"
55 #include "content/child/resource_dispatcher.h"
56 #include "content/child/resource_scheduling_filter.h"
57 #include "content/child/runtime_features.h"
58 #include "content/child/thread_safe_sender.h"
59 #include "content/child/web_database_observer_impl.h"
60 #include "content/child/worker_task_runner.h"
61 #include "content/common/child_process_messages.h"
62 #include "content/common/content_constants_internal.h"
63 #include "content/common/database_messages.h"
64 #include "content/common/dom_storage/dom_storage_messages.h"
65 #include "content/common/frame_messages.h"
66 #include "content/common/gpu/client/context_provider_command_buffer.h"
67 #include "content/common/gpu/client/gpu_channel_host.h"
68 #include "content/common/gpu/gpu_messages.h"
69 #include "content/common/gpu/gpu_process_launch_causes.h"
70 #include "content/common/render_frame_setup.mojom.h"
71 #include "content/common/resource_messages.h"
72 #include "content/common/service_worker/embedded_worker_setup.mojom.h"
73 #include "content/common/view_messages.h"
74 #include "content/common/worker_messages.h"
75 #include "content/public/common/content_constants.h"
76 #include "content/public/common/content_paths.h"
77 #include "content/public/common/content_switches.h"
78 #include "content/public/common/mojo_channel_switches.h"
79 #include "content/public/common/renderer_preferences.h"
80 #include "content/public/common/url_constants.h"
81 #include "content/public/renderer/content_renderer_client.h"
82 #include "content/public/renderer/render_process_observer.h"
83 #include "content/public/renderer/render_view_visitor.h"
84 #include "content/renderer/bluetooth/bluetooth_message_filter.h"
85 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
86 #include "content/renderer/cache_storage/cache_storage_dispatcher.h"
87 #include "content/renderer/cache_storage/cache_storage_message_filter.h"
88 #include "content/renderer/devtools/devtools_agent_filter.h"
89 #include "content/renderer/devtools/v8_sampling_profiler.h"
90 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
91 #include "content/renderer/dom_storage/webstoragearea_impl.h"
92 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
93 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
94 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
95 #include "content/renderer/gpu/compositor_output_surface.h"
96 #include "content/renderer/input/input_event_filter.h"
97 #include "content/renderer/input/input_handler_manager.h"
98 #include "content/renderer/input/main_thread_input_event_filter.h"
99 #include "content/renderer/media/aec_dump_message_filter.h"
100 #include "content/renderer/media/audio_input_message_filter.h"
101 #include "content/renderer/media/audio_message_filter.h"
102 #include "content/renderer/media/audio_renderer_mixer_manager.h"
103 #include "content/renderer/media/media_stream_center.h"
104 #include "content/renderer/media/midi_message_filter.h"
105 #include "content/renderer/media/render_media_client.h"
106 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
107 #include "content/renderer/media/video_capture_impl_manager.h"
108 #include "content/renderer/media/video_capture_message_filter.h"
109 #include "content/renderer/net_info_helper.h"
110 #include "content/renderer/p2p/socket_dispatcher.h"
111 #include "content/renderer/raster_worker_pool.h"
112 #include "content/renderer/render_frame_proxy.h"
113 #include "content/renderer/render_process_impl.h"
114 #include "content/renderer/render_view_impl.h"
115 #include "content/renderer/renderer_blink_platform_impl.h"
116 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
117 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
118 #include "content/renderer/service_worker/service_worker_context_client.h"
119 #include "content/renderer/service_worker/service_worker_context_message_filter.h"
120 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
121 #include "gin/public/debug.h"
122 #include "gpu/GLES2/gl2extchromium.h"
123 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
124 #include "ipc/ipc_channel_handle.h"
125 #include "ipc/ipc_platform_file.h"
126 #include "ipc/mojo/ipc_channel_mojo.h"
127 #include "media/base/audio_hardware_config.h"
128 #include "media/base/media.h"
129 #include "media/renderers/gpu_video_accelerator_factories.h"
130 #include "mojo/common/common_type_converters.h"
131 #include "net/base/net_errors.h"
132 #include "net/base/port_util.h"
133 #include "skia/ext/event_tracer_impl.h"
134 #include "skia/ext/skia_memory_dump_provider.h"
135 #include "third_party/WebKit/public/platform/WebImageGenerator.h"
136 #include "third_party/WebKit/public/platform/WebString.h"
137 #include "third_party/WebKit/public/platform/WebThread.h"
138 #include "third_party/WebKit/public/web/WebCache.h"
139 #include "third_party/WebKit/public/web/WebColorName.h"
140 #include "third_party/WebKit/public/web/WebDatabase.h"
141 #include "third_party/WebKit/public/web/WebDocument.h"
142 #include "third_party/WebKit/public/web/WebFrame.h"
143 #include "third_party/WebKit/public/web/WebImageCache.h"
144 #include "third_party/WebKit/public/web/WebKit.h"
145 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
146 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
147 #include "third_party/WebKit/public/web/WebScriptController.h"
148 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
149 #include "third_party/WebKit/public/web/WebView.h"
150 #include "third_party/icu/source/i18n/unicode/timezone.h"
151 #include "third_party/mojo/src/mojo/public/cpp/bindings/strong_binding.h"
152 #include "third_party/skia/include/core/SkGraphics.h"
153 #include "ui/base/layout.h"
154 #include "ui/base/ui_base_switches.h"
155 #include "v8/include/v8.h"
157 #if defined(OS_ANDROID)
158 #include <cpu-features.h>
159 #include "content/renderer/android/synchronous_compositor_factory.h"
160 #include "content/renderer/media/android/renderer_demuxer_android.h"
161 #endif
163 #if defined(OS_MACOSX)
164 #include "base/mac/mac_util.h"
165 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
166 #endif
168 #if defined(OS_POSIX)
169 #include "ipc/ipc_channel_posix.h"
170 #endif
172 #if defined(OS_WIN)
173 #include <windows.h>
174 #include <objbase.h>
175 #else
176 // TODO(port)
177 #include "content/child/npapi/np_channel_base.h"
178 #endif
180 #if defined(ENABLE_PLUGINS)
181 #include "content/renderer/npapi/plugin_channel_host.h"
182 #endif
184 #if defined(ENABLE_WEBRTC)
185 #include "content/renderer/media/peer_connection_tracker.h"
186 #include "content/renderer/media/rtc_peer_connection_handler.h"
187 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
188 #include "content/renderer/media/webrtc_identity_service.h"
189 #endif
191 #ifdef ENABLE_VTUNE_JIT_INTERFACE
192 #include "v8/src/third_party/vtune/v8-vtune.h"
193 #endif
195 using base::ThreadRestrictions;
196 using blink::WebDocument;
197 using blink::WebFrame;
198 using blink::WebNetworkStateNotifier;
199 using blink::WebRuntimeFeatures;
200 using blink::WebScriptController;
201 using blink::WebSecurityPolicy;
202 using blink::WebString;
203 using blink::WebView;
205 namespace content {
207 namespace {
209 const int64 kInitialIdleHandlerDelayMs = 1000;
210 const int64 kLongIdleHandlerDelayMs = 30*1000;
212 #if defined(OS_ANDROID)
213 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
214 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
215 // induced work takes but a fraction (~1/4) of the overall frame budget.
216 const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
217 #else
218 const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
219 #endif
220 const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
222 // Maximum allocation size allowed for image scaling filters that
223 // require pre-scaling. Skia will fallback to a filter that doesn't
224 // require pre-scaling if the default filter would require an
225 // allocation that exceeds this limit.
226 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
228 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
229 // incorrectly from the wrong thread.
230 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
231 lazy_tls = LAZY_INSTANCE_INITIALIZER;
233 class RenderViewZoomer : public RenderViewVisitor {
234 public:
235 RenderViewZoomer(const std::string& scheme,
236 const std::string& host,
237 double zoom_level) : scheme_(scheme),
238 host_(host),
239 zoom_level_(zoom_level) {
242 bool Visit(RenderView* render_view) override {
243 WebView* webview = render_view->GetWebView();
244 RenderViewImpl* render_view_impl =
245 static_cast<RenderViewImpl*>(render_view);
246 // Remote frames don't host documents.
247 // TODO(wjmaclean) Although it seems likely that a frame without a
248 // document can safely early-out here, we should confirm this is truly
249 // the case. https://crbug.com/477007
250 if (webview->mainFrame()->isWebRemoteFrame())
251 return true;
253 WebDocument document = webview->mainFrame()->document();
255 // Don't set zoom level for full-page plugin since they don't use the same
256 // zoom settings.
257 if (document.isPluginDocument())
258 return true;
259 GURL url(document.url());
260 // Empty scheme works as wildcard that matches any scheme,
261 if ((net::GetHostOrSpecFromURL(url) == host_) &&
262 (scheme_.empty() || scheme_ == url.scheme()) &&
263 !render_view_impl->uses_temporary_zoom_level()) {
264 webview->hidePopups();
265 render_view_impl->SetZoomLevel(zoom_level_);
267 return true;
270 private:
271 const std::string scheme_;
272 const std::string host_;
273 const double zoom_level_;
275 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
278 std::string HostToCustomHistogramSuffix(const std::string& host) {
279 if (host == "mail.google.com")
280 return ".gmail";
281 if (host == "docs.google.com" || host == "drive.google.com")
282 return ".docs";
283 if (host == "plus.google.com")
284 return ".plus";
285 if (host == "inbox.google.com")
286 return ".inbox";
287 return std::string();
290 void* CreateHistogram(
291 const char *name, int min, int max, size_t buckets) {
292 if (min <= 0)
293 min = 1;
294 std::string histogram_name;
295 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
296 if (render_thread_impl) { // Can be null in tests.
297 histogram_name = render_thread_impl->
298 histogram_customizer()->ConvertToCustomHistogramName(name);
299 } else {
300 histogram_name = std::string(name);
302 base::HistogramBase* histogram = base::Histogram::FactoryGet(
303 histogram_name, min, max, buckets,
304 base::Histogram::kUmaTargetedHistogramFlag);
305 return histogram;
308 void AddHistogramSample(void* hist, int sample) {
309 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
310 histogram->Add(sample);
313 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
314 const gfx::Size& size) {
315 return ChildThreadImpl::current()->shared_bitmap_manager()->
316 AllocateSharedBitmap(size);
319 void EnableBlinkPlatformLogChannels(const std::string& channels) {
320 if (channels.empty())
321 return;
322 base::StringTokenizer t(channels, ", ");
323 while (t.GetNext())
324 blink::enableLogChannel(t.token().c_str());
327 void NotifyTimezoneChangeOnThisThread() {
328 v8::Isolate* isolate = v8::Isolate::GetCurrent();
329 if (!isolate)
330 return;
331 v8::Date::DateTimeConfigurationChangeNotification(isolate);
334 void LowMemoryNotificationOnThisThread() {
335 v8::Isolate* isolate = v8::Isolate::GetCurrent();
336 if (!isolate)
337 return;
338 isolate->LowMemoryNotification();
341 class RenderFrameSetupImpl : public RenderFrameSetup {
342 public:
343 explicit RenderFrameSetupImpl(
344 mojo::InterfaceRequest<RenderFrameSetup> request)
345 : routing_id_highmark_(-1), binding_(this, request.Pass()) {}
347 void ExchangeServiceProviders(
348 int32_t frame_routing_id,
349 mojo::InterfaceRequest<mojo::ServiceProvider> services,
350 mojo::ServiceProviderPtr exposed_services)
351 override {
352 // TODO(morrita): This is for investigating http://crbug.com/415059 and
353 // should be removed once it is fixed.
354 CHECK_LT(routing_id_highmark_, frame_routing_id);
355 routing_id_highmark_ = frame_routing_id;
357 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
358 // We can receive a GetServiceProviderForFrame message for a frame not yet
359 // created due to a race between the message and a ViewMsg_New IPC that
360 // triggers creation of the RenderFrame we want.
361 if (!frame) {
362 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
363 frame_routing_id, services.Pass(), exposed_services.Pass());
364 return;
367 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
370 private:
371 int32_t routing_id_highmark_;
372 mojo::StrongBinding<RenderFrameSetup> binding_;
375 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
376 new RenderFrameSetupImpl(request.Pass());
379 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
380 blink::WebGraphicsContext3D::Attributes attributes;
381 attributes.shareResources = true;
382 attributes.depth = false;
383 attributes.stencil = false;
384 attributes.antialias = false;
385 attributes.noAutomaticFlushes = true;
386 return attributes;
389 void SetupEmbeddedWorkerOnWorkerThread(
390 mojo::InterfaceRequest<mojo::ServiceProvider> services,
391 mojo::ServiceProviderPtr exposed_services) {
392 ServiceWorkerContextClient* client =
393 ServiceWorkerContextClient::ThreadSpecificInstance();
394 // It is possible for client to be null if for some reason the worker died
395 // before this call made it to the worker thread. In that case just do
396 // nothing and let mojo close the connection.
397 if (!client)
398 return;
399 client->BindServiceRegistry(services.Pass(), exposed_services.Pass());
402 class EmbeddedWorkerSetupImpl : public EmbeddedWorkerSetup {
403 public:
404 explicit EmbeddedWorkerSetupImpl(
405 mojo::InterfaceRequest<EmbeddedWorkerSetup> request)
406 : binding_(this, request.Pass()) {}
408 void ExchangeServiceProviders(
409 int32_t thread_id,
410 mojo::InterfaceRequest<mojo::ServiceProvider> services,
411 mojo::ServiceProviderPtr exposed_services) override {
412 WorkerTaskRunner::Instance()->GetTaskRunnerFor(thread_id)->PostTask(
413 FROM_HERE,
414 base::Bind(&SetupEmbeddedWorkerOnWorkerThread, base::Passed(&services),
415 base::Passed(&exposed_services)));
418 private:
419 mojo::StrongBinding<EmbeddedWorkerSetup> binding_;
422 void CreateEmbeddedWorkerSetup(
423 mojo::InterfaceRequest<EmbeddedWorkerSetup> request) {
424 new EmbeddedWorkerSetupImpl(request.Pass());
427 void StringToUintVector(const std::string& str, std::vector<unsigned>* vector) {
428 DCHECK(vector->empty());
429 std::vector<std::string> pieces = base::SplitString(
430 str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
431 DCHECK_EQ(pieces.size(), static_cast<size_t>(gfx::BufferFormat::LAST) + 1);
432 for (size_t i = 0; i < pieces.size(); ++i) {
433 unsigned number = 0;
434 bool succeed = base::StringToUint(pieces[i], &number);
435 DCHECK(succeed);
436 vector->push_back(number);
440 } // namespace
442 // For measuring memory usage after each task. Behind a command line flag.
443 class MemoryObserver : public base::MessageLoop::TaskObserver {
444 public:
445 MemoryObserver() {}
446 ~MemoryObserver() override {}
448 void WillProcessTask(const base::PendingTask& pending_task) override {}
450 void DidProcessTask(const base::PendingTask& pending_task) override {
451 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
454 private:
455 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
458 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
459 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
460 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
461 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
464 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
466 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
467 const std::string& host, size_t view_count) {
468 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
469 switches::kDisableHistogramCustomizer)) {
470 return;
472 // Check if all RenderViews are displaying a page from the same host. If there
473 // is only one RenderView, the common host is this view's host. If there are
474 // many, check if this one shares the common host of the other
475 // RenderViews. It's ok to not detect some cases where the RenderViews share a
476 // common host. This information is only used for producing custom histograms.
477 if (view_count == 1)
478 SetCommonHost(host);
479 else if (host != common_host_)
480 SetCommonHost(std::string());
483 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
484 const char* histogram_name) const {
485 std::string name(histogram_name);
486 if (!common_host_histogram_suffix_.empty() &&
487 custom_histograms_.find(name) != custom_histograms_.end())
488 name += common_host_histogram_suffix_;
489 return name;
492 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
493 const std::string& host) {
494 if (host != common_host_) {
495 common_host_ = host;
496 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
497 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
501 // static
502 RenderThreadImpl* RenderThreadImpl::Create(
503 const InProcessChildThreadParams& params) {
504 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler =
505 scheduler::RendererScheduler::Create();
506 return new RenderThreadImpl(params, renderer_scheduler.Pass());
509 // static
510 RenderThreadImpl* RenderThreadImpl::Create(
511 scoped_ptr<base::MessageLoop> main_message_loop,
512 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler) {
513 return new RenderThreadImpl(main_message_loop.Pass(),
514 renderer_scheduler.Pass());
517 RenderThreadImpl* RenderThreadImpl::current() {
518 return lazy_tls.Pointer()->Get();
521 RenderThreadImpl::RenderThreadImpl(
522 const InProcessChildThreadParams& params,
523 scoped_ptr<scheduler::RendererScheduler> scheduler)
524 : ChildThreadImpl(Options::Builder()
525 .InBrowserProcess(params)
526 .UseMojoChannel(ShouldUseMojoChannel())
527 .Build()),
528 renderer_scheduler_(scheduler.Pass()),
529 raster_worker_pool_(new RasterWorkerPool()) {
530 Init();
533 // When we run plugins in process, we actually run them on the render thread,
534 // which means that we need to make the render thread pump UI events.
535 RenderThreadImpl::RenderThreadImpl(
536 scoped_ptr<base::MessageLoop> main_message_loop,
537 scoped_ptr<scheduler::RendererScheduler> scheduler)
538 : ChildThreadImpl(Options::Builder()
539 .UseMojoChannel(ShouldUseMojoChannel())
540 .Build()),
541 renderer_scheduler_(scheduler.Pass()),
542 main_message_loop_(main_message_loop.Pass()),
543 raster_worker_pool_(new RasterWorkerPool()) {
544 Init();
547 void RenderThreadImpl::Init() {
548 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
550 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
551 base::PlatformThread::CurrentId(),
552 kTraceEventRendererMainThreadSortIndex);
554 #if defined(OS_MACOSX) || defined(OS_ANDROID)
555 // On Mac and Android, the select popups are rendered by the browser.
556 blink::WebView::setUseExternalPopupMenus(true);
557 #endif
559 lazy_tls.Pointer()->Set(this);
561 // Register this object as the main thread.
562 ChildProcess::current()->set_main_thread(this);
564 // In single process the single process is all there is.
565 notify_webkit_of_modal_loop_ = true;
566 webkit_shared_timer_suspended_ = false;
567 widget_count_ = 0;
568 hidden_widget_count_ = 0;
569 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
570 idle_notifications_to_skip_ = 0;
571 layout_test_mode_ = false;
573 appcache_dispatcher_.reset(
574 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
575 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
576 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
577 thread_safe_sender()));
578 main_thread_cache_storage_dispatcher_.reset(
579 new CacheStorageDispatcher(thread_safe_sender()));
580 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
582 // Note: This may reorder messages from the ResourceDispatcher with respect to
583 // other subsystems.
584 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
585 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
586 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
587 kMaxResourceRequestsPerFlushWhenThrottled));
588 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
590 media_stream_center_ = NULL;
592 db_message_filter_ = new DBMessageFilter();
593 AddFilter(db_message_filter_.get());
595 vc_manager_.reset(new VideoCaptureImplManager());
596 AddFilter(vc_manager_->video_capture_message_filter());
598 browser_plugin_manager_.reset(new BrowserPluginManager());
599 AddObserver(browser_plugin_manager_.get());
601 #if defined(ENABLE_WEBRTC)
602 peer_connection_tracker_.reset(new PeerConnectionTracker());
603 AddObserver(peer_connection_tracker_.get());
605 p2p_socket_dispatcher_ =
606 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
607 AddFilter(p2p_socket_dispatcher_.get());
609 webrtc_identity_service_.reset(new WebRTCIdentityService());
611 aec_dump_message_filter_ = new AecDumpMessageFilter(
612 GetIOMessageLoopProxy(), message_loop()->task_runner());
613 AddFilter(aec_dump_message_filter_.get());
615 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
616 p2p_socket_dispatcher_.get()));
617 #endif // defined(ENABLE_WEBRTC)
619 audio_input_message_filter_ =
620 new AudioInputMessageFilter(GetIOMessageLoopProxy());
621 AddFilter(audio_input_message_filter_.get());
623 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
624 AddFilter(audio_message_filter_.get());
626 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
627 AddFilter(midi_message_filter_.get());
629 bluetooth_message_filter_ = new BluetoothMessageFilter(thread_safe_sender());
630 AddFilter(bluetooth_message_filter_->GetFilter());
632 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
634 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
636 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
638 GetContentClient()->renderer()->RenderThreadStarted();
640 InitSkiaEventTracer();
641 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
642 skia::SkiaMemoryDumpProvider::GetInstance());
644 const base::CommandLine& command_line =
645 *base::CommandLine::ForCurrentProcess();
647 cc::LayerSettings layer_settings;
648 if (command_line.HasSwitch(switches::kEnableCompositorAnimationTimelines))
649 layer_settings.use_compositor_animation_timelines = true;
650 cc_blink::WebLayerImpl::SetLayerSettings(layer_settings);
651 cc::SetClientNameForMetrics("Renderer");
653 is_threaded_animation_enabled_ =
654 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
656 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
657 is_persistent_gpu_memory_buffer_enabled_ =
658 command_line.HasSwitch(switches::kEnablePersistentGpuMemoryBuffer);
660 #if defined(OS_MACOSX) && !defined(OS_IOS)
661 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
662 if (is_elastic_overscroll_enabled_) {
663 base::ScopedCFTypeRef<CFStringRef> key(
664 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
665 Boolean key_exists = false;
666 Boolean value = CFPreferencesGetAppBooleanValue(
667 key, kCFPreferencesCurrentApplication, &key_exists);
668 if (key_exists && !value)
669 is_elastic_overscroll_enabled_ = false;
671 #else
672 is_elastic_overscroll_enabled_ = false;
673 #endif
675 std::string image_texture_target_string =
676 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
677 StringToUintVector(image_texture_target_string, &use_image_texture_targets_);
679 if (command_line.HasSwitch(switches::kDisableLCDText)) {
680 is_lcd_text_enabled_ = false;
681 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
682 is_lcd_text_enabled_ = true;
683 } else {
684 #if defined(OS_ANDROID)
685 is_lcd_text_enabled_ = false;
686 #else
687 is_lcd_text_enabled_ = true;
688 #endif
691 is_gpu_rasterization_enabled_ =
692 command_line.HasSwitch(switches::kEnableGpuRasterization);
693 is_gpu_rasterization_forced_ =
694 command_line.HasSwitch(switches::kForceGpuRasterization);
696 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
697 std::string string_value = command_line.GetSwitchValueASCII(
698 switches::kGpuRasterizationMSAASampleCount);
699 bool parsed_msaa_sample_count =
700 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
701 DCHECK(parsed_msaa_sample_count) << string_value;
702 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
703 } else {
704 gpu_rasterization_msaa_sample_count_ = -1;
707 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
708 is_distance_field_text_enabled_ = false;
709 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
710 is_distance_field_text_enabled_ = true;
711 } else {
712 is_distance_field_text_enabled_ = false;
715 // Note that under Linux, the media library will normally already have
716 // been initialized by the Zygote before this instance became a Renderer.
717 media::InitializeMediaLibrary();
719 memory_pressure_listener_.reset(new base::MemoryPressureListener(
720 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
722 is_gather_pixel_refs_enabled_ = false;
724 int num_raster_threads = 0;
725 std::string string_value =
726 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
727 bool parsed_num_raster_threads =
728 base::StringToInt(string_value, &num_raster_threads);
729 DCHECK(parsed_num_raster_threads) << string_value;
730 DCHECK_GT(num_raster_threads, 0);
732 // Note: Currently, gathering of pixel refs when using a single
733 // raster thread doesn't provide any benefit. This might change
734 // in the future but we avoid it for now to reduce the cost of
735 // Picture::Create.
736 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
738 base::SimpleThread::Options thread_options;
739 #if defined(OS_ANDROID) || defined(OS_LINUX)
740 if (!command_line.HasSwitch(
741 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
742 thread_options.set_priority(base::ThreadPriority::BACKGROUND);
744 #endif
746 raster_worker_pool_->Start(num_raster_threads, thread_options);
748 // TODO(boliu): In single process, browser main loop should set up the
749 // discardable memory manager, and should skip this if kSingleProcess.
750 // See crbug.com/503724.
751 base::DiscardableMemoryAllocator::SetInstance(
752 ChildThreadImpl::discardable_shared_memory_manager());
754 service_registry()->AddService<RenderFrameSetup>(
755 base::Bind(CreateRenderFrameSetup));
756 service_registry()->AddService<EmbeddedWorkerSetup>(
757 base::Bind(CreateEmbeddedWorkerSetup));
759 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
762 RenderThreadImpl::~RenderThreadImpl() {
765 void RenderThreadImpl::Shutdown() {
766 FOR_EACH_OBSERVER(
767 RenderProcessObserver, observers_, OnRenderProcessShutdown());
769 ChildThreadImpl::Shutdown();
771 if (memory_observer_) {
772 message_loop()->RemoveTaskObserver(memory_observer_.get());
773 memory_observer_.reset();
776 // Wait for all databases to be closed.
777 if (blink_platform_impl_) {
778 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
779 // processing timer events while we're already in the process of shutting
780 // down blink, put a ScopePageLoadDeferrer on the stack.
781 WebView::willEnterModalLoop();
782 blink_platform_impl_->web_database_observer_impl()
783 ->WaitForAllDatabasesToClose();
784 WebView::didExitModalLoop();
787 // Shutdown in reverse of the initialization order.
788 if (devtools_agent_message_filter_.get()) {
789 RemoveFilter(devtools_agent_message_filter_.get());
790 devtools_agent_message_filter_ = NULL;
793 RemoveFilter(audio_input_message_filter_.get());
794 audio_input_message_filter_ = NULL;
796 #if defined(ENABLE_WEBRTC)
797 RTCPeerConnectionHandler::DestructAllHandlers();
798 // |peer_connection_factory_| cannot be deleted until after the main message
799 // loop has been destroyed. This is because there may be pending tasks that
800 // hold on to objects produced by the PC factory that depend on threads owned
801 // by the PC factory. Once those tasks have been freed, the factory can be
802 // deleted.
803 #endif
804 RemoveFilter(vc_manager_->video_capture_message_filter());
805 vc_manager_.reset();
807 RemoveFilter(db_message_filter_.get());
808 db_message_filter_ = NULL;
810 // Shutdown the file thread if it's running.
811 if (file_thread_)
812 file_thread_->Stop();
814 if (compositor_message_filter_.get()) {
815 RemoveFilter(compositor_message_filter_.get());
816 compositor_message_filter_ = NULL;
819 media_thread_.reset();
821 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
822 RemoveFilter(audio_message_filter_.get());
823 audio_message_filter_ = NULL;
825 compositor_thread_.reset();
827 raster_worker_pool_->Shutdown();
829 main_input_callback_.Cancel();
830 input_handler_manager_.reset();
831 if (input_event_filter_.get()) {
832 RemoveFilter(input_event_filter_.get());
833 input_event_filter_ = NULL;
836 // RemoveEmbeddedWorkerRoute may be called while deleting
837 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
838 // RenderThreadImpl.
839 embedded_worker_dispatcher_.reset();
841 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
842 // hold pointers to V8 objects (e.g., via pending requests).
843 main_thread_indexed_db_dispatcher_.reset();
845 main_thread_compositor_task_runner_ = NULL;
847 // Context providers must be released prior to destroying the GPU channel.
848 gpu_va_context_provider_ = nullptr;
849 shared_main_thread_contexts_ = nullptr;
851 if (gpu_channel_.get())
852 gpu_channel_->DestroyChannel();
854 // TODO(port)
855 #if defined(OS_WIN)
856 // Clean up plugin channels before this thread goes away.
857 NPChannelBase::CleanupChannels();
858 #endif
860 // Shut down the message loop and the renderer scheduler before shutting down
861 // Blink. This prevents a scenario where a pending task in the message loop
862 // accesses Blink objects after Blink shuts down.
863 // This must be at the very end of the shutdown sequence. You must not touch
864 // the message loop after this.
865 renderer_scheduler_->Shutdown();
866 main_message_loop_.reset();
867 if (blink_platform_impl_)
868 blink::shutdown();
870 lazy_tls.Pointer()->Set(NULL);
873 bool RenderThreadImpl::Send(IPC::Message* msg) {
874 // Certain synchronous messages cannot always be processed synchronously by
875 // the browser, e.g., putting up UI and waiting for the user. This could cause
876 // a complete hang of Chrome if a windowed plugin is trying to communicate
877 // with the renderer thread since the browser's UI thread could be stuck
878 // (within a Windows API call) trying to synchronously communicate with the
879 // plugin. The remedy is to pump messages on this thread while the browser
880 // is processing this request. This creates an opportunity for re-entrancy
881 // into WebKit, so we need to take care to disable callbacks, timers, and
882 // pending network loads that could trigger such callbacks.
883 bool pumping_events = false;
884 if (msg->is_sync()) {
885 if (msg->is_caller_pumping_messages()) {
886 pumping_events = true;
890 bool notify_webkit_of_modal_loop = true; // default value
891 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
893 #if defined(ENABLE_PLUGINS)
894 int render_view_id = MSG_ROUTING_NONE;
895 #endif
897 if (pumping_events) {
898 renderer_scheduler_->SuspendTimerQueue();
900 if (notify_webkit_of_modal_loop)
901 WebView::willEnterModalLoop();
902 #if defined(ENABLE_PLUGINS)
903 RenderViewImpl* render_view =
904 RenderViewImpl::FromRoutingID(msg->routing_id());
905 if (render_view) {
906 render_view_id = msg->routing_id();
907 PluginChannelHost::Broadcast(
908 new PluginMsg_SignalModalDialogEvent(render_view_id));
910 #endif
913 bool rv = ChildThreadImpl::Send(msg);
915 if (pumping_events) {
916 #if defined(ENABLE_PLUGINS)
917 if (render_view_id != MSG_ROUTING_NONE) {
918 PluginChannelHost::Broadcast(
919 new PluginMsg_ResetModalDialogEvent(render_view_id));
921 #endif
923 if (notify_webkit_of_modal_loop)
924 WebView::didExitModalLoop();
926 renderer_scheduler_->ResumeTimerQueue();
929 return rv;
932 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
933 return channel();
936 std::string RenderThreadImpl::GetLocale() {
937 // The browser process should have passed the locale to the renderer via the
938 // --lang command line flag.
939 const base::CommandLine& parsed_command_line =
940 *base::CommandLine::ForCurrentProcess();
941 const std::string& lang =
942 parsed_command_line.GetSwitchValueASCII(switches::kLang);
943 DCHECK(!lang.empty());
944 return lang;
947 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
948 return sync_message_filter();
951 scoped_refptr<base::SingleThreadTaskRunner>
952 RenderThreadImpl::GetIOMessageLoopProxy() {
953 return ChildProcess::current()->io_task_runner();
956 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
957 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
958 PendingRenderFrameConnectMap::iterator it =
959 pending_render_frame_connects_.find(routing_id);
960 if (it == pending_render_frame_connects_.end())
961 return;
963 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
964 if (!frame)
965 return;
967 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
968 mojo::InterfaceRequest<mojo::ServiceProvider> services(
969 connection->services().Pass());
970 mojo::ServiceProviderPtr exposed_services(
971 connection->exposed_services().Pass());
972 exposed_services.set_connection_error_handler(mojo::Closure());
973 pending_render_frame_connects_.erase(it);
975 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
978 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
979 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
982 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
983 IPC::Listener* listener) {
984 AddRoute(routing_id, listener);
985 if (devtools_agent_message_filter_.get()) {
986 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
987 routing_id);
991 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
992 RemoveRoute(routing_id);
993 if (devtools_agent_message_filter_.get()) {
994 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
995 routing_id);
999 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
1000 int routing_id,
1001 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1002 mojo::ServiceProviderPtr exposed_services) {
1003 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
1004 pending_render_frame_connects_.insert(std::make_pair(
1005 routing_id,
1006 make_scoped_refptr(new PendingRenderFrameConnect(
1007 routing_id, services.Pass(), exposed_services.Pass()))));
1008 CHECK(result.second) << "Inserting a duplicate item.";
1011 int RenderThreadImpl::GenerateRoutingID() {
1012 int routing_id = MSG_ROUTING_NONE;
1013 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
1014 return routing_id;
1017 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
1018 channel()->AddFilter(filter);
1021 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
1022 channel()->RemoveFilter(filter);
1025 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
1026 observers_.AddObserver(observer);
1029 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
1030 observers_.RemoveObserver(observer);
1033 void RenderThreadImpl::SetResourceDispatcherDelegate(
1034 ResourceDispatcherDelegate* delegate) {
1035 resource_dispatcher()->set_delegate(delegate);
1038 void RenderThreadImpl::SetResourceDispatchTaskQueue(
1039 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
1040 // Add a filter that forces resource messages to be dispatched via a
1041 // particular task runner.
1042 resource_scheduling_filter_ =
1043 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
1044 channel()->AddFilter(resource_scheduling_filter_.get());
1046 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1047 // same queue to ensure tasks are executed in the expected order.
1048 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1049 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1052 void RenderThreadImpl::EnsureWebKitInitialized() {
1053 if (blink_platform_impl_)
1054 return;
1056 const base::CommandLine& command_line =
1057 *base::CommandLine::ForCurrentProcess();
1059 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1060 if (command_line.HasSwitch(switches::kEnableVtune))
1061 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1062 #endif
1064 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1066 blink_platform_impl_.reset(
1067 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1068 blink::initialize(blink_platform_impl_.get());
1070 v8::Isolate* isolate = blink::mainThreadIsolate();
1071 isolate->SetCreateHistogramFunction(CreateHistogram);
1072 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1074 main_thread_compositor_task_runner_ =
1075 renderer_scheduler_->CompositorTaskRunner();
1077 main_input_callback_.Reset(
1078 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1079 base::Unretained(this)));
1081 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1083 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1084 if (enable) {
1085 #if defined(OS_ANDROID)
1086 if (SynchronousCompositorFactory* factory =
1087 SynchronousCompositorFactory::GetInstance())
1088 compositor_task_runner_ = factory->GetCompositorTaskRunner();
1089 #endif
1090 if (!compositor_task_runner_.get()) {
1091 compositor_thread_.reset(new base::Thread("Compositor"));
1092 base::Thread::Options compositor_thread_options;
1093 #if defined(OS_ANDROID)
1094 compositor_thread_options.priority = base::ThreadPriority::DISPLAY;
1095 #endif
1096 compositor_thread_->StartWithOptions(compositor_thread_options);
1097 compositor_task_runner_ = compositor_thread_->task_runner();
1098 compositor_task_runner_->PostTask(
1099 FROM_HERE,
1100 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1101 false));
1104 InputHandlerManagerClient* input_handler_manager_client = NULL;
1105 #if defined(OS_ANDROID)
1106 if (SynchronousCompositorFactory* factory =
1107 SynchronousCompositorFactory::GetInstance()) {
1108 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1110 #endif
1111 if (!input_handler_manager_client) {
1112 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1113 new InputEventFilter(main_input_callback_.callback(),
1114 main_thread_compositor_task_runner_,
1115 compositor_task_runner_));
1116 input_handler_manager_client = compositor_input_event_filter.get();
1117 input_event_filter_ = compositor_input_event_filter;
1119 input_handler_manager_.reset(new InputHandlerManager(
1120 compositor_task_runner_, input_handler_manager_client,
1121 renderer_scheduler_.get()));
1124 if (!input_event_filter_.get()) {
1125 // Always provide an input event filter implementation to ensure consistent
1126 // input event scheduling and prioritization.
1127 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1128 // MainThreadInputEventFilter, crbug.com/436057.
1129 input_event_filter_ = new MainThreadInputEventFilter(
1130 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1132 AddFilter(input_event_filter_.get());
1134 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
1135 if (enable)
1136 compositor_impl_side_task_runner = compositor_task_runner_;
1137 else
1138 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
1140 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1141 compositor_impl_side_task_runner.get());
1142 AddFilter(compositor_message_filter_.get());
1144 RenderThreadImpl::RegisterSchemes();
1146 EnableBlinkPlatformLogChannels(
1147 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1149 RenderMediaClient::Initialize();
1151 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1153 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1154 AddFilter(devtools_agent_message_filter_.get());
1156 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1158 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1159 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1161 renderer_scheduler_->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1162 GetContentClient()
1163 ->renderer()
1164 ->AllowTimerSuspensionWhenProcessBackgrounded());
1166 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1168 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1169 kImageCacheSingleAllocationByteLimit);
1171 // Hook up blink's codecs so skia can call them
1172 SkGraphics::SetImageGeneratorFromEncodedFactory(
1173 blink::WebImageGenerator::create);
1175 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1176 memory_observer_.reset(new MemoryObserver());
1177 message_loop()->AddTaskObserver(memory_observer_.get());
1180 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1181 std::string allowed_ports =
1182 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1183 net::SetExplicitlyAllowedPorts(allowed_ports);
1187 void RenderThreadImpl::RegisterSchemes() {
1188 // swappedout:
1189 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1190 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1191 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1193 // chrome:
1194 WebString chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme));
1195 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1196 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1197 chrome_scheme);
1198 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme);
1199 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme);
1201 // chrome-devtools:
1202 WebString devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme));
1203 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
1206 void RenderThreadImpl::NotifyTimezoneChange() {
1207 NotifyTimezoneChangeOnThisThread();
1208 RenderThread::Get()->PostTaskToAllWebWorkers(
1209 base::Bind(&NotifyTimezoneChangeOnThisThread));
1212 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1213 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1216 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1217 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1220 scoped_ptr<base::SharedMemory>
1221 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1222 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1225 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1226 return shared_bitmap_manager();
1229 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1230 EnsureWebKitInitialized();
1231 WebScriptController::registerExtension(extension);
1234 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1235 idle_notification_delay_in_ms_ = initial_delay_ms;
1236 idle_timer_.Stop();
1237 idle_timer_.Start(FROM_HERE,
1238 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1239 this, &RenderThreadImpl::IdleHandler);
1242 void RenderThreadImpl::IdleHandler() {
1243 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1244 GetContentClient()->renderer()->
1245 RunIdleHandlerWhenWidgetsHidden();
1246 if (run_in_foreground_tab) {
1247 if (idle_notifications_to_skip_ > 0) {
1248 --idle_notifications_to_skip_;
1249 } else {
1250 ReleaseFreeMemory();
1252 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1253 return;
1256 ReleaseFreeMemory();
1258 // Continue the idle timer if the webkit shared timer is not suspended or
1259 // something is left to do.
1260 bool continue_timer = !webkit_shared_timer_suspended_;
1262 if (blink::mainThreadIsolate() &&
1263 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1264 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1265 continue_timer = true;
1268 // Schedule next invocation. When the tab is originally hidden, an invocation
1269 // is scheduled for kInitialIdleHandlerDelayMs in
1270 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1271 // After that, idle calls can be much less frequent, so run at a maximum of
1272 // once every kLongIdleHandlerDelayMs.
1273 // Dampen the delay using the algorithm (if delay is in seconds):
1274 // delay = delay + 1 / (delay + 2)
1275 // Using floor(delay) has a dampening effect such as:
1276 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1277 // If the delay is in milliseconds, the above formula is equivalent to:
1278 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1279 // which is equivalent to
1280 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1281 if (continue_timer) {
1282 ScheduleIdleHandler(
1283 std::max(kLongIdleHandlerDelayMs,
1284 idle_notification_delay_in_ms_ +
1285 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1287 } else {
1288 idle_timer_.Stop();
1291 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1294 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1295 return idle_notification_delay_in_ms_;
1298 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1299 int64 idle_notification_delay_in_ms) {
1300 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1303 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1304 child_histogram_message_filter()->SendHistograms(sequence_number);
1307 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1308 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1311 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1312 bool result = false;
1313 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1314 return result;
1317 void RenderThreadImpl::PostponeIdleNotification() {
1318 idle_notifications_to_skip_ = 2;
1321 scoped_refptr<media::GpuVideoAcceleratorFactories>
1322 RenderThreadImpl::GetGpuFactories() {
1323 DCHECK(IsMainThread());
1325 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1327 #if defined(OS_ANDROID)
1328 if (SynchronousCompositorFactory::GetInstance()) {
1329 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1330 DLOG(WARNING) << "Accelerated video decoding is not explicitly disabled, "
1331 "but is not supported by in-process rendering";
1333 return NULL;
1335 #endif
1337 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1338 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1339 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1340 GetMediaThreadTaskRunner();
1341 if (!gpu_va_context_provider_.get() ||
1342 gpu_va_context_provider_->DestroyedOnMainThread()) {
1343 if (!gpu_channel_host.get()) {
1344 gpu_channel_host = EstablishGpuChannelSync(
1345 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1347 blink::WebGraphicsContext3D::Attributes attributes;
1348 bool lose_context_when_out_of_memory = false;
1349 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1350 make_scoped_ptr(
1351 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1352 gpu_channel_host.get(), attributes,
1353 lose_context_when_out_of_memory,
1354 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1355 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1356 NULL)),
1357 GPU_VIDEO_ACCELERATOR_CONTEXT);
1359 if (gpu_va_context_provider_.get()) {
1360 const bool enable_video_accelerator =
1361 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1362 const bool enable_gpu_memory_buffer_video_frames =
1363 #if defined(OS_MACOSX)
1364 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames);
1365 #else
1366 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
1367 #endif
1368 std::string image_texture_target_string =
1369 cmd_line->GetSwitchValueASCII(switches::kVideoImageTextureTarget);
1370 unsigned image_texture_target = 0;
1371 const bool parsed_image_texture_target =
1372 base::StringToUint(image_texture_target_string, &image_texture_target);
1373 DCHECK(parsed_image_texture_target);
1374 CHECK(gpu_channel_.get()) << "Have gpu_va_context_provider but no "
1375 "gpu_channel_. See crbug.com/495185.";
1376 CHECK(gpu_channel_host.get()) << "Have gpu_va_context_provider but lost "
1377 "gpu_channel_. See crbug.com/495185.";
1379 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1380 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_,
1381 enable_gpu_memory_buffer_video_frames, image_texture_target,
1382 enable_video_accelerator);
1384 return gpu_factories;
1387 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1388 RenderThreadImpl::CreateOffscreenContext3d() {
1389 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1390 bool lose_context_when_out_of_memory = true;
1392 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1393 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1394 return make_scoped_ptr(
1395 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1396 gpu_channel_host.get(),
1397 attributes,
1398 lose_context_when_out_of_memory,
1399 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1400 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1401 NULL));
1404 scoped_refptr<cc_blink::ContextProviderWebContext>
1405 RenderThreadImpl::SharedMainThreadContextProvider() {
1406 DCHECK(IsMainThread());
1407 if (!shared_main_thread_contexts_.get() ||
1408 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1409 shared_main_thread_contexts_ = NULL;
1410 #if defined(OS_ANDROID)
1411 SynchronousCompositorFactory* factory =
1412 SynchronousCompositorFactory::GetInstance();
1413 if (factory && factory->OverrideWithFactory()) {
1414 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1415 GetOffscreenAttribs(), "Offscreen-MainThread");
1417 #endif
1418 if (!shared_main_thread_contexts_.get()) {
1419 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1420 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT);
1422 if (shared_main_thread_contexts_.get() &&
1423 !shared_main_thread_contexts_->BindToCurrentThread())
1424 shared_main_thread_contexts_ = NULL;
1426 return shared_main_thread_contexts_;
1429 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1430 if (!audio_renderer_mixer_manager_) {
1431 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1432 GetAudioHardwareConfig()));
1435 return audio_renderer_mixer_manager_.get();
1438 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1439 if (!audio_hardware_config_) {
1440 media::AudioParameters input_params;
1441 media::AudioParameters output_params;
1442 Send(new ViewHostMsg_GetAudioHardwareConfig(
1443 &input_params, &output_params));
1445 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1446 input_params, output_params));
1449 return audio_hardware_config_.get();
1452 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1453 return ChildProcess::current()->GetShutDownEvent();
1456 #if defined(OS_WIN)
1457 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1458 const base::string16& str) {
1459 Send(new FrameHostMsg_PreCacheFontCharacters(log_font, str));
1462 #endif // OS_WIN
1464 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1465 return service_registry();
1468 bool RenderThreadImpl::IsGpuRasterizationForced() {
1469 return is_gpu_rasterization_forced_;
1472 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1473 return is_gpu_rasterization_enabled_;
1476 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1477 return gpu_rasterization_msaa_sample_count_;
1480 bool RenderThreadImpl::IsLcdTextEnabled() {
1481 return is_lcd_text_enabled_;
1484 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1485 return is_distance_field_text_enabled_;
1488 bool RenderThreadImpl::IsZeroCopyEnabled() {
1489 return is_zero_copy_enabled_;
1492 bool RenderThreadImpl::IsPersistentGpuMemoryBufferEnabled() {
1493 return is_persistent_gpu_memory_buffer_enabled_;
1496 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1497 return is_elastic_overscroll_enabled_;
1500 std::vector<unsigned> RenderThreadImpl::GetImageTextureTargets() {
1501 return use_image_texture_targets_;
1504 scoped_refptr<base::SingleThreadTaskRunner>
1505 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1506 return main_thread_compositor_task_runner_;
1509 scoped_refptr<base::SingleThreadTaskRunner>
1510 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1511 return compositor_task_runner_;
1514 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1515 return gpu_memory_buffer_manager();
1518 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1519 return renderer_scheduler_.get();
1522 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1523 return SharedMainThreadContextProvider().get();
1526 scoped_ptr<cc::BeginFrameSource>
1527 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1528 #if defined(OS_ANDROID)
1529 if (SynchronousCompositorFactory* factory =
1530 SynchronousCompositorFactory::GetInstance()) {
1531 return factory->CreateExternalBeginFrameSource(routing_id);
1533 #endif
1534 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1535 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1538 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1539 return raster_worker_pool_->GetTaskGraphRunner();
1542 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1543 return is_gather_pixel_refs_enabled_;
1546 bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1547 return is_threaded_animation_enabled_;
1550 bool RenderThreadImpl::IsMainThread() {
1551 return !!current();
1554 scoped_refptr<base::SingleThreadTaskRunner>
1555 RenderThreadImpl::GetIOThreadTaskRunner() {
1556 return io_thread_task_runner_;
1559 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1560 size_t size) {
1561 return scoped_ptr<base::SharedMemory>(
1562 HostAllocateSharedMemoryBuffer(size));
1565 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1566 int32 surface_id,
1567 const GPUCreateCommandBufferConfig& init_params,
1568 int32 route_id) {
1569 TRACE_EVENT1("gpu",
1570 "RenderThreadImpl::CreateViewCommandBuffer",
1571 "surface_id",
1572 surface_id);
1574 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1575 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1576 surface_id,
1577 init_params,
1578 route_id,
1579 &result);
1581 // Allow calling this from the compositor thread.
1582 thread_safe_sender()->Send(message);
1584 return result;
1587 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1588 notify_webkit_of_modal_loop_ = false;
1591 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1592 base::ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1593 RenderProcessObserver* observer;
1594 while ((observer = it.GetNext()) != NULL) {
1595 if (observer->OnControlMessageReceived(msg))
1596 return true;
1599 // Some messages are handled by delegates.
1600 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1601 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1602 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1603 return true;
1606 bool handled = true;
1607 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1608 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1609 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1610 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1611 OnSetZoomLevelForCurrentURL)
1612 // TODO(port): removed from render_messages_internal.h;
1613 // is there a new non-windows message I should add here?
1614 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1615 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1616 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1617 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1618 #if defined(OS_ANDROID)
1619 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1620 OnSetWebKitSharedTimersSuspended)
1621 #endif
1622 #if defined(OS_MACOSX)
1623 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1624 #endif
1625 #if defined(ENABLE_PLUGINS)
1626 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1627 #endif
1628 IPC_MESSAGE_UNHANDLED(handled = false)
1629 IPC_END_MESSAGE_MAP()
1630 return handled;
1633 void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded) {
1634 ChildThreadImpl::OnProcessBackgrounded(backgrounded);
1636 if (backgrounded)
1637 renderer_scheduler_->OnRendererBackgrounded();
1638 else
1639 renderer_scheduler_->OnRendererForegrounded();
1642 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params) {
1643 CompositorDependencies* compositor_deps = this;
1644 RenderFrameImpl::CreateFrame(
1645 params.routing_id, params.proxy_routing_id, params.opener_routing_id,
1646 params.parent_routing_id, params.previous_sibling_routing_id,
1647 params.replication_state, compositor_deps, params.widget_params);
1650 void RenderThreadImpl::OnCreateNewFrameProxy(
1651 int routing_id,
1652 int render_view_routing_id,
1653 int opener_routing_id,
1654 int parent_routing_id,
1655 const FrameReplicationState& replicated_state) {
1656 RenderFrameProxy::CreateFrameProxy(routing_id, render_view_routing_id,
1657 opener_routing_id, parent_routing_id,
1658 replicated_state);
1661 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1662 const std::string& host,
1663 double zoom_level) {
1664 RenderViewZoomer zoomer(scheme, host, zoom_level);
1665 RenderView::ForEach(&zoomer);
1668 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1669 EnsureWebKitInitialized();
1670 CompositorDependencies* compositor_deps = this;
1671 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1672 RenderViewImpl::Create(compositor_deps, params, false);
1675 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1676 CauseForGpuLaunch cause_for_gpu_launch) {
1677 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1679 if (gpu_channel_.get()) {
1680 // Do nothing if we already have a GPU channel or are already
1681 // establishing one.
1682 if (!gpu_channel_->IsLost())
1683 return gpu_channel_.get();
1685 // Recreate the channel if it has been lost.
1686 gpu_channel_->DestroyChannel();
1687 gpu_channel_ = NULL;
1690 // Ask the browser for the channel name.
1691 int client_id = 0;
1692 IPC::ChannelHandle channel_handle;
1693 gpu::GPUInfo gpu_info;
1694 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1695 &client_id,
1696 &channel_handle,
1697 &gpu_info)) ||
1698 #if defined(OS_POSIX)
1699 channel_handle.socket.fd == -1 ||
1700 #endif
1701 channel_handle.name.empty()) {
1702 // Otherwise cancel the connection.
1703 return NULL;
1706 GetContentClient()->SetGpuInfo(gpu_info);
1708 // Cache some variables that are needed on the compositor thread for our
1709 // implementation of GpuChannelHostFactory.
1710 io_thread_task_runner_ = ChildProcess::current()->io_task_runner();
1712 gpu_channel_ =
1713 GpuChannelHost::Create(this,
1714 client_id,
1715 gpu_info,
1716 channel_handle,
1717 ChildProcess::current()->GetShutDownEvent(),
1718 gpu_memory_buffer_manager());
1719 return gpu_channel_.get();
1722 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1723 blink::WebMediaStreamCenterClient* client) {
1724 #if defined(ENABLE_WEBRTC)
1725 if (!media_stream_center_) {
1726 media_stream_center_ = GetContentClient()->renderer()
1727 ->OverrideCreateWebMediaStreamCenter(client);
1728 if (!media_stream_center_) {
1729 scoped_ptr<MediaStreamCenter> media_stream_center(
1730 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1731 media_stream_center_ = media_stream_center.release();
1734 #endif
1735 return media_stream_center_;
1738 #if defined(ENABLE_WEBRTC)
1739 PeerConnectionDependencyFactory*
1740 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1741 return peer_connection_factory_.get();
1743 #endif
1745 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1746 if (!gpu_channel_.get())
1747 return NULL;
1749 if (gpu_channel_->IsLost())
1750 return NULL;
1752 return gpu_channel_.get();
1755 #if defined(ENABLE_PLUGINS)
1756 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1757 EnsureWebKitInitialized();
1758 // The call below will cause a GetPlugins call with refresh=true, but at this
1759 // point we already know that the browser has refreshed its list, so disable
1760 // refresh temporarily to prevent each renderer process causing the list to be
1761 // regenerated.
1762 blink_platform_impl_->set_plugin_refresh_allowed(false);
1763 blink::resetPluginCache(reload_pages);
1764 blink_platform_impl_->set_plugin_refresh_allowed(true);
1766 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1768 #endif
1770 void RenderThreadImpl::OnNetworkTypeChanged(
1771 net::NetworkChangeNotifier::ConnectionType type) {
1772 EnsureWebKitInitialized();
1773 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1774 WebNetworkStateNotifier::setOnLine(online);
1775 FOR_EACH_OBSERVER(
1776 RenderProcessObserver, observers_, NetworkStateChanged(online));
1777 WebNetworkStateNotifier::setWebConnectionType(
1778 NetConnectionTypeToWebConnectionType(type));
1781 void RenderThreadImpl::OnUpdateTimezone(const std::string& zone_id) {
1782 if (!blink_platform_impl_)
1783 return;
1784 if (!zone_id.empty()) {
1785 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
1786 icu::UnicodeString::fromUTF8(zone_id));
1787 icu::TimeZone::adoptDefault(new_zone);
1788 VLOG(1) << "ICU default timezone is set to " << zone_id;
1790 NotifyTimezoneChange();
1793 #if defined(OS_ANDROID)
1794 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1795 EnsureWebKitInitialized();
1796 if (suspend) {
1797 renderer_scheduler_->SuspendTimerQueue();
1798 } else {
1799 renderer_scheduler_->ResumeTimerQueue();
1801 webkit_shared_timer_suspended_ = suspend;
1803 #endif
1805 #if defined(OS_MACOSX)
1806 void RenderThreadImpl::OnUpdateScrollbarTheme(
1807 const ViewMsg_UpdateScrollbarTheme_Params& params) {
1808 EnsureWebKitInitialized();
1809 static_cast<WebScrollbarBehaviorImpl*>(
1810 blink_platform_impl_->scrollbarBehavior())
1811 ->set_jump_on_track_click(params.jump_on_track_click);
1813 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
1814 params.initial_button_delay, params.autoscroll_button_delay,
1815 params.preferred_scroller_style, params.redraw,
1816 params.scroll_animation_enabled, params.button_placement);
1818 #endif
1820 void RenderThreadImpl::OnCreateNewSharedWorker(
1821 const WorkerProcessMsg_CreateWorker_Params& params) {
1822 // EmbeddedSharedWorkerStub will self-destruct.
1823 new EmbeddedSharedWorkerStub(params.url,
1824 params.name,
1825 params.content_security_policy,
1826 params.security_policy_type,
1827 params.pause_on_start,
1828 params.route_id);
1831 void RenderThreadImpl::OnMemoryPressure(
1832 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1833 ReleaseFreeMemory();
1835 // Do not call into blink if it is not initialized.
1836 if (blink_platform_impl_) {
1837 blink::WebCache::pruneAll();
1839 if (blink::mainThreadIsolate()) {
1840 // Trigger full v8 garbage collection on memory pressure notifications.
1841 // This will potentially hang the renderer for a long time, however, when
1842 // we receive a memory pressure notification, we might be about to be
1843 // killed.
1844 blink::mainThreadIsolate()->LowMemoryNotification();
1845 RenderThread::Get()->PostTaskToAllWebWorkers(
1846 base::Bind(&LowMemoryNotificationOnThisThread));
1849 if (memory_pressure_level ==
1850 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1851 // Clear the image cache.
1852 blink::WebImageCache::clear();
1854 // Purge Skia font cache, by setting it to 0 and then again to the
1855 // previous limit.
1856 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1857 SkGraphics::SetFontCacheLimit(font_cache_limit);
1862 scoped_refptr<base::SingleThreadTaskRunner>
1863 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1864 DCHECK(message_loop() == base::MessageLoop::current());
1865 if (!file_thread_) {
1866 file_thread_.reset(new base::Thread("Renderer::FILE"));
1867 file_thread_->Start();
1869 return file_thread_->task_runner();
1872 scoped_refptr<base::SingleThreadTaskRunner>
1873 RenderThreadImpl::GetMediaThreadTaskRunner() {
1874 DCHECK(message_loop() == base::MessageLoop::current());
1875 if (!media_thread_) {
1876 media_thread_.reset(new base::Thread("Media"));
1877 media_thread_->Start();
1879 #if defined(OS_ANDROID)
1880 renderer_demuxer_ = new RendererDemuxerAndroid();
1881 AddFilter(renderer_demuxer_.get());
1882 #endif
1884 return media_thread_->task_runner();
1887 base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
1888 return raster_worker_pool_.get();
1891 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1892 blink_platform_impl_->sampleGamepads(*data);
1895 bool RenderThreadImpl::RendererIsHidden() const {
1896 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1899 void RenderThreadImpl::WidgetCreated() {
1900 bool renderer_was_hidden = RendererIsHidden();
1901 widget_count_++;
1902 if (renderer_was_hidden)
1903 OnRendererVisible();
1906 void RenderThreadImpl::WidgetDestroyed() {
1907 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1908 // unhidden before WidgetDestroyed is called.
1909 DCHECK_GT(widget_count_, 0);
1910 DCHECK_GT(widget_count_, hidden_widget_count_);
1911 widget_count_--;
1912 if (RendererIsHidden())
1913 OnRendererHidden();
1916 void RenderThreadImpl::WidgetHidden() {
1917 DCHECK_LT(hidden_widget_count_, widget_count_);
1918 hidden_widget_count_++;
1919 if (RendererIsHidden())
1920 OnRendererHidden();
1923 void RenderThreadImpl::WidgetRestored() {
1924 bool renderer_was_hidden = RendererIsHidden();
1925 DCHECK_GT(hidden_widget_count_, 0);
1926 hidden_widget_count_--;
1927 if (renderer_was_hidden)
1928 OnRendererVisible();
1931 void RenderThreadImpl::OnRendererHidden() {
1932 renderer_scheduler_->OnRendererHidden();
1934 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1935 // scheduled by the RendererScheduler - http://crbug.com/469210.
1936 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1937 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1940 void RenderThreadImpl::OnRendererVisible() {
1941 renderer_scheduler_->OnRendererVisible();
1943 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1944 return;
1946 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1949 void RenderThreadImpl::ReleaseFreeMemory() {
1950 base::allocator::ReleaseFreeMemory();
1951 discardable_shared_memory_manager()->ReleaseFreeMemory();
1953 if (blink_platform_impl_)
1954 blink::decommitFreeableMemory();
1957 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1958 int routing_id,
1959 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1960 mojo::ServiceProviderPtr exposed_services)
1961 : routing_id_(routing_id),
1962 services_(services.Pass()),
1963 exposed_services_(exposed_services.Pass()) {
1964 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1965 // is received. In that case, the RenderFrameHost should close the connection,
1966 // which is detected by setting an error handler on |exposed_services_|.
1967 exposed_services_.set_connection_error_handler(base::Bind(
1968 &RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError,
1969 base::Unretained(this)));
1972 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1975 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1976 size_t erased =
1977 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1978 routing_id_);
1979 DCHECK_EQ(1u, erased);
1982 } // namespace content