Further cleanup of some assets
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blob071c62227f1d30a45fcb36a9483f688aba00092e
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/switches.h"
36 #include "cc/blink/web_external_bitmap_impl.h"
37 #include "cc/blink/web_layer_impl.h"
38 #include "cc/raster/task_graph_runner.h"
39 #include "cc/trees/layer_tree_settings.h"
40 #include "components/scheduler/renderer/renderer_scheduler.h"
41 #include "content/child/appcache/appcache_dispatcher.h"
42 #include "content/child/appcache/appcache_frontend_impl.h"
43 #include "content/child/child_discardable_shared_memory_manager.h"
44 #include "content/child/child_gpu_memory_buffer_manager.h"
45 #include "content/child/child_histogram_message_filter.h"
46 #include "content/child/child_resource_message_filter.h"
47 #include "content/child/child_shared_bitmap_manager.h"
48 #include "content/child/content_child_helpers.h"
49 #include "content/child/db_message_filter.h"
50 #include "content/child/indexed_db/indexed_db_dispatcher.h"
51 #include "content/child/indexed_db/indexed_db_message_filter.h"
52 #include "content/child/npapi/npobject_util.h"
53 #include "content/child/plugin_messages.h"
54 #include "content/child/resource_dispatcher.h"
55 #include "content/child/resource_scheduling_filter.h"
56 #include "content/child/runtime_features.h"
57 #include "content/child/thread_safe_sender.h"
58 #include "content/child/web_database_observer_impl.h"
59 #include "content/child/worker_task_runner.h"
60 #include "content/common/child_process_messages.h"
61 #include "content/common/content_constants_internal.h"
62 #include "content/common/database_messages.h"
63 #include "content/common/dom_storage/dom_storage_messages.h"
64 #include "content/common/frame_messages.h"
65 #include "content/common/gpu/client/context_provider_command_buffer.h"
66 #include "content/common/gpu/client/gpu_channel_host.h"
67 #include "content/common/gpu/gpu_messages.h"
68 #include "content/common/gpu/gpu_process_launch_causes.h"
69 #include "content/common/render_frame_setup.mojom.h"
70 #include "content/common/resource_messages.h"
71 #include "content/common/service_worker/embedded_worker_setup.mojom.h"
72 #include "content/common/view_messages.h"
73 #include "content/common/worker_messages.h"
74 #include "content/public/common/content_constants.h"
75 #include "content/public/common/content_paths.h"
76 #include "content/public/common/content_switches.h"
77 #include "content/public/common/mojo_channel_switches.h"
78 #include "content/public/common/renderer_preferences.h"
79 #include "content/public/common/url_constants.h"
80 #include "content/public/renderer/content_renderer_client.h"
81 #include "content/public/renderer/render_process_observer.h"
82 #include "content/public/renderer/render_view_visitor.h"
83 #include "content/renderer/bluetooth/bluetooth_message_filter.h"
84 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
85 #include "content/renderer/cache_storage/cache_storage_dispatcher.h"
86 #include "content/renderer/cache_storage/cache_storage_message_filter.h"
87 #include "content/renderer/devtools/devtools_agent_filter.h"
88 #include "content/renderer/devtools/v8_sampling_profiler.h"
89 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
90 #include "content/renderer/dom_storage/webstoragearea_impl.h"
91 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
92 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
93 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
94 #include "content/renderer/gpu/compositor_output_surface.h"
95 #include "content/renderer/input/input_event_filter.h"
96 #include "content/renderer/input/input_handler_manager.h"
97 #include "content/renderer/input/main_thread_input_event_filter.h"
98 #include "content/renderer/media/aec_dump_message_filter.h"
99 #include "content/renderer/media/audio_input_message_filter.h"
100 #include "content/renderer/media/audio_message_filter.h"
101 #include "content/renderer/media/audio_renderer_mixer_manager.h"
102 #include "content/renderer/media/media_stream_center.h"
103 #include "content/renderer/media/midi_message_filter.h"
104 #include "content/renderer/media/render_media_client.h"
105 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
106 #include "content/renderer/media/video_capture_impl_manager.h"
107 #include "content/renderer/media/video_capture_message_filter.h"
108 #include "content/renderer/net_info_helper.h"
109 #include "content/renderer/p2p/socket_dispatcher.h"
110 #include "content/renderer/raster_worker_pool.h"
111 #include "content/renderer/render_frame_proxy.h"
112 #include "content/renderer/render_process_impl.h"
113 #include "content/renderer/render_view_impl.h"
114 #include "content/renderer/renderer_blink_platform_impl.h"
115 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
116 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
117 #include "content/renderer/service_worker/service_worker_context_client.h"
118 #include "content/renderer/service_worker/service_worker_context_message_filter.h"
119 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
120 #include "gin/public/debug.h"
121 #include "gpu/GLES2/gl2extchromium.h"
122 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
123 #include "ipc/ipc_channel_handle.h"
124 #include "ipc/ipc_platform_file.h"
125 #include "ipc/mojo/ipc_channel_mojo.h"
126 #include "media/base/audio_hardware_config.h"
127 #include "media/base/media.h"
128 #include "media/renderers/gpu_video_accelerator_factories.h"
129 #include "mojo/common/common_type_converters.h"
130 #include "net/base/net_errors.h"
131 #include "net/base/port_util.h"
132 #include "skia/ext/event_tracer_impl.h"
133 #include "skia/ext/skia_memory_dump_provider.h"
134 #include "third_party/WebKit/public/platform/WebImageGenerator.h"
135 #include "third_party/WebKit/public/platform/WebString.h"
136 #include "third_party/WebKit/public/platform/WebThread.h"
137 #include "third_party/WebKit/public/web/WebCache.h"
138 #include "third_party/WebKit/public/web/WebColorName.h"
139 #include "third_party/WebKit/public/web/WebDatabase.h"
140 #include "third_party/WebKit/public/web/WebDocument.h"
141 #include "third_party/WebKit/public/web/WebFrame.h"
142 #include "third_party/WebKit/public/web/WebImageCache.h"
143 #include "third_party/WebKit/public/web/WebKit.h"
144 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
145 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
146 #include "third_party/WebKit/public/web/WebScriptController.h"
147 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
148 #include "third_party/WebKit/public/web/WebView.h"
149 #include "third_party/icu/source/i18n/unicode/timezone.h"
150 #include "third_party/mojo/src/mojo/public/cpp/bindings/strong_binding.h"
151 #include "third_party/skia/include/core/SkGraphics.h"
152 #include "ui/base/layout.h"
153 #include "ui/base/ui_base_switches.h"
154 #include "v8/include/v8.h"
156 #if defined(OS_ANDROID)
157 #include <cpu-features.h>
158 #include "content/renderer/android/synchronous_compositor_factory.h"
159 #include "content/renderer/media/android/renderer_demuxer_android.h"
160 #endif
162 #if defined(OS_MACOSX)
163 #include "base/mac/mac_util.h"
164 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
165 #endif
167 #if defined(OS_POSIX)
168 #include "ipc/ipc_channel_posix.h"
169 #endif
171 #if defined(OS_WIN)
172 #include <windows.h>
173 #include <objbase.h>
174 #else
175 // TODO(port)
176 #include "content/child/npapi/np_channel_base.h"
177 #endif
179 #if defined(ENABLE_PLUGINS)
180 #include "content/renderer/npapi/plugin_channel_host.h"
181 #endif
183 #if defined(ENABLE_WEBRTC)
184 #include "content/renderer/media/peer_connection_tracker.h"
185 #include "content/renderer/media/rtc_peer_connection_handler.h"
186 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
187 #include "content/renderer/media/webrtc_identity_service.h"
188 #endif
190 #ifdef ENABLE_VTUNE_JIT_INTERFACE
191 #include "v8/src/third_party/vtune/v8-vtune.h"
192 #endif
194 using base::ThreadRestrictions;
195 using blink::WebDocument;
196 using blink::WebFrame;
197 using blink::WebNetworkStateNotifier;
198 using blink::WebRuntimeFeatures;
199 using blink::WebScriptController;
200 using blink::WebSecurityPolicy;
201 using blink::WebString;
202 using blink::WebView;
204 namespace content {
206 namespace {
208 const int64 kInitialIdleHandlerDelayMs = 1000;
209 const int64 kLongIdleHandlerDelayMs = 30*1000;
211 #if defined(OS_ANDROID)
212 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
213 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
214 // induced work takes but a fraction (~1/4) of the overall frame budget.
215 const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
216 #else
217 const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
218 #endif
219 const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
221 // Maximum allocation size allowed for image scaling filters that
222 // require pre-scaling. Skia will fallback to a filter that doesn't
223 // require pre-scaling if the default filter would require an
224 // allocation that exceeds this limit.
225 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
227 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
228 // incorrectly from the wrong thread.
229 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
230 lazy_tls = LAZY_INSTANCE_INITIALIZER;
232 class RenderViewZoomer : public RenderViewVisitor {
233 public:
234 RenderViewZoomer(const std::string& scheme,
235 const std::string& host,
236 double zoom_level) : scheme_(scheme),
237 host_(host),
238 zoom_level_(zoom_level) {
241 bool Visit(RenderView* render_view) override {
242 WebView* webview = render_view->GetWebView();
243 RenderViewImpl* render_view_impl =
244 static_cast<RenderViewImpl*>(render_view);
245 // Remote frames don't host documents.
246 // TODO(wjmaclean) Although it seems likely that a frame without a
247 // document can safely early-out here, we should confirm this is truly
248 // the case. https://crbug.com/477007
249 if (webview->mainFrame()->isWebRemoteFrame())
250 return true;
252 WebDocument document = webview->mainFrame()->document();
254 // Don't set zoom level for full-page plugin since they don't use the same
255 // zoom settings.
256 if (document.isPluginDocument())
257 return true;
258 GURL url(document.url());
259 // Empty scheme works as wildcard that matches any scheme,
260 if ((net::GetHostOrSpecFromURL(url) == host_) &&
261 (scheme_.empty() || scheme_ == url.scheme()) &&
262 !render_view_impl->uses_temporary_zoom_level()) {
263 webview->hidePopups();
264 render_view_impl->SetZoomLevel(zoom_level_);
266 return true;
269 private:
270 const std::string scheme_;
271 const std::string host_;
272 const double zoom_level_;
274 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
277 std::string HostToCustomHistogramSuffix(const std::string& host) {
278 if (host == "mail.google.com")
279 return ".gmail";
280 if (host == "docs.google.com" || host == "drive.google.com")
281 return ".docs";
282 if (host == "plus.google.com")
283 return ".plus";
284 if (host == "inbox.google.com")
285 return ".inbox";
286 return std::string();
289 void* CreateHistogram(
290 const char *name, int min, int max, size_t buckets) {
291 if (min <= 0)
292 min = 1;
293 std::string histogram_name;
294 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
295 if (render_thread_impl) { // Can be null in tests.
296 histogram_name = render_thread_impl->
297 histogram_customizer()->ConvertToCustomHistogramName(name);
298 } else {
299 histogram_name = std::string(name);
301 base::HistogramBase* histogram = base::Histogram::FactoryGet(
302 histogram_name, min, max, buckets,
303 base::Histogram::kUmaTargetedHistogramFlag);
304 return histogram;
307 void AddHistogramSample(void* hist, int sample) {
308 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
309 histogram->Add(sample);
312 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
313 const gfx::Size& size) {
314 return ChildThreadImpl::current()->shared_bitmap_manager()->
315 AllocateSharedBitmap(size);
318 void EnableBlinkPlatformLogChannels(const std::string& channels) {
319 if (channels.empty())
320 return;
321 base::StringTokenizer t(channels, ", ");
322 while (t.GetNext())
323 blink::enableLogChannel(t.token().c_str());
326 void NotifyTimezoneChangeOnThisThread() {
327 v8::Isolate* isolate = v8::Isolate::GetCurrent();
328 if (!isolate)
329 return;
330 v8::Date::DateTimeConfigurationChangeNotification(isolate);
333 void LowMemoryNotificationOnThisThread() {
334 v8::Isolate* isolate = v8::Isolate::GetCurrent();
335 if (!isolate)
336 return;
337 isolate->LowMemoryNotification();
340 class RenderFrameSetupImpl : public RenderFrameSetup {
341 public:
342 explicit RenderFrameSetupImpl(
343 mojo::InterfaceRequest<RenderFrameSetup> request)
344 : routing_id_highmark_(-1), binding_(this, request.Pass()) {}
346 void ExchangeServiceProviders(
347 int32_t frame_routing_id,
348 mojo::InterfaceRequest<mojo::ServiceProvider> services,
349 mojo::ServiceProviderPtr exposed_services)
350 override {
351 // TODO(morrita): This is for investigating http://crbug.com/415059 and
352 // should be removed once it is fixed.
353 CHECK_LT(routing_id_highmark_, frame_routing_id);
354 routing_id_highmark_ = frame_routing_id;
356 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
357 // We can receive a GetServiceProviderForFrame message for a frame not yet
358 // created due to a race between the message and a ViewMsg_New IPC that
359 // triggers creation of the RenderFrame we want.
360 if (!frame) {
361 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
362 frame_routing_id, services.Pass(), exposed_services.Pass());
363 return;
366 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
369 private:
370 int32_t routing_id_highmark_;
371 mojo::StrongBinding<RenderFrameSetup> binding_;
374 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
375 new RenderFrameSetupImpl(request.Pass());
378 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
379 blink::WebGraphicsContext3D::Attributes attributes;
380 attributes.shareResources = true;
381 attributes.depth = false;
382 attributes.stencil = false;
383 attributes.antialias = false;
384 attributes.noAutomaticFlushes = true;
385 return attributes;
388 void SetupEmbeddedWorkerOnWorkerThread(
389 mojo::InterfaceRequest<mojo::ServiceProvider> services,
390 mojo::ServiceProviderPtr exposed_services) {
391 ServiceWorkerContextClient* client =
392 ServiceWorkerContextClient::ThreadSpecificInstance();
393 // It is possible for client to be null if for some reason the worker died
394 // before this call made it to the worker thread. In that case just do
395 // nothing and let mojo close the connection.
396 if (!client)
397 return;
398 client->BindServiceRegistry(services.Pass(), exposed_services.Pass());
401 class EmbeddedWorkerSetupImpl : public EmbeddedWorkerSetup {
402 public:
403 explicit EmbeddedWorkerSetupImpl(
404 mojo::InterfaceRequest<EmbeddedWorkerSetup> request)
405 : binding_(this, request.Pass()) {}
407 void ExchangeServiceProviders(
408 int32_t thread_id,
409 mojo::InterfaceRequest<mojo::ServiceProvider> services,
410 mojo::ServiceProviderPtr exposed_services) override {
411 WorkerTaskRunner::Instance()->GetTaskRunnerFor(thread_id)->PostTask(
412 FROM_HERE,
413 base::Bind(&SetupEmbeddedWorkerOnWorkerThread, base::Passed(&services),
414 base::Passed(&exposed_services)));
417 private:
418 mojo::StrongBinding<EmbeddedWorkerSetup> binding_;
421 void CreateEmbeddedWorkerSetup(
422 mojo::InterfaceRequest<EmbeddedWorkerSetup> request) {
423 new EmbeddedWorkerSetupImpl(request.Pass());
426 void StringToUintVector(const std::string& str, std::vector<unsigned>* vector) {
427 DCHECK(vector->empty());
428 std::vector<std::string> pieces = base::SplitString(
429 str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
430 DCHECK_EQ(pieces.size(), static_cast<size_t>(gfx::BufferFormat::LAST) + 1);
431 for (size_t i = 0; i < pieces.size(); ++i) {
432 unsigned number = 0;
433 bool succeed = base::StringToUint(pieces[i], &number);
434 DCHECK(succeed);
435 vector->push_back(number);
439 } // namespace
441 // For measuring memory usage after each task. Behind a command line flag.
442 class MemoryObserver : public base::MessageLoop::TaskObserver {
443 public:
444 MemoryObserver() {}
445 ~MemoryObserver() override {}
447 void WillProcessTask(const base::PendingTask& pending_task) override {}
449 void DidProcessTask(const base::PendingTask& pending_task) override {
450 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
453 private:
454 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
457 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
458 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
459 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
460 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
463 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
465 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
466 const std::string& host, size_t view_count) {
467 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
468 switches::kDisableHistogramCustomizer)) {
469 return;
471 // Check if all RenderViews are displaying a page from the same host. If there
472 // is only one RenderView, the common host is this view's host. If there are
473 // many, check if this one shares the common host of the other
474 // RenderViews. It's ok to not detect some cases where the RenderViews share a
475 // common host. This information is only used for producing custom histograms.
476 if (view_count == 1)
477 SetCommonHost(host);
478 else if (host != common_host_)
479 SetCommonHost(std::string());
482 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
483 const char* histogram_name) const {
484 std::string name(histogram_name);
485 if (!common_host_histogram_suffix_.empty() &&
486 custom_histograms_.find(name) != custom_histograms_.end())
487 name += common_host_histogram_suffix_;
488 return name;
491 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
492 const std::string& host) {
493 if (host != common_host_) {
494 common_host_ = host;
495 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
496 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
500 // static
501 RenderThreadImpl* RenderThreadImpl::Create(
502 const InProcessChildThreadParams& params) {
503 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler =
504 scheduler::RendererScheduler::Create();
505 return new RenderThreadImpl(params, renderer_scheduler.Pass());
508 // static
509 RenderThreadImpl* RenderThreadImpl::Create(
510 scoped_ptr<base::MessageLoop> main_message_loop,
511 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler) {
512 return new RenderThreadImpl(main_message_loop.Pass(),
513 renderer_scheduler.Pass());
516 RenderThreadImpl* RenderThreadImpl::current() {
517 return lazy_tls.Pointer()->Get();
520 RenderThreadImpl::RenderThreadImpl(
521 const InProcessChildThreadParams& params,
522 scoped_ptr<scheduler::RendererScheduler> scheduler)
523 : ChildThreadImpl(Options::Builder()
524 .InBrowserProcess(params)
525 .UseMojoChannel(ShouldUseMojoChannel())
526 .Build()),
527 renderer_scheduler_(scheduler.Pass()),
528 raster_worker_pool_(new RasterWorkerPool()) {
529 Init();
532 // When we run plugins in process, we actually run them on the render thread,
533 // which means that we need to make the render thread pump UI events.
534 RenderThreadImpl::RenderThreadImpl(
535 scoped_ptr<base::MessageLoop> main_message_loop,
536 scoped_ptr<scheduler::RendererScheduler> scheduler)
537 : ChildThreadImpl(Options::Builder()
538 .UseMojoChannel(ShouldUseMojoChannel())
539 .Build()),
540 renderer_scheduler_(scheduler.Pass()),
541 main_message_loop_(main_message_loop.Pass()),
542 raster_worker_pool_(new RasterWorkerPool()) {
543 Init();
546 void RenderThreadImpl::Init() {
547 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
549 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
550 base::PlatformThread::CurrentId(),
551 kTraceEventRendererMainThreadSortIndex);
553 #if defined(OS_MACOSX) || defined(OS_ANDROID)
554 // On Mac and Android, the select popups are rendered by the browser.
555 blink::WebView::setUseExternalPopupMenus(true);
556 #endif
558 lazy_tls.Pointer()->Set(this);
560 // Register this object as the main thread.
561 ChildProcess::current()->set_main_thread(this);
563 // In single process the single process is all there is.
564 notify_webkit_of_modal_loop_ = true;
565 webkit_shared_timer_suspended_ = false;
566 widget_count_ = 0;
567 hidden_widget_count_ = 0;
568 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
569 idle_notifications_to_skip_ = 0;
570 layout_test_mode_ = false;
572 appcache_dispatcher_.reset(
573 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
574 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
575 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
576 thread_safe_sender()));
577 main_thread_cache_storage_dispatcher_.reset(
578 new CacheStorageDispatcher(thread_safe_sender()));
579 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
581 // Note: This may reorder messages from the ResourceDispatcher with respect to
582 // other subsystems.
583 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
584 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
585 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
586 kMaxResourceRequestsPerFlushWhenThrottled));
587 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
589 media_stream_center_ = NULL;
591 db_message_filter_ = new DBMessageFilter();
592 AddFilter(db_message_filter_.get());
594 vc_manager_.reset(new VideoCaptureImplManager());
595 AddFilter(vc_manager_->video_capture_message_filter());
597 browser_plugin_manager_.reset(new BrowserPluginManager());
598 AddObserver(browser_plugin_manager_.get());
600 #if defined(ENABLE_WEBRTC)
601 peer_connection_tracker_.reset(new PeerConnectionTracker());
602 AddObserver(peer_connection_tracker_.get());
604 p2p_socket_dispatcher_ =
605 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
606 AddFilter(p2p_socket_dispatcher_.get());
608 webrtc_identity_service_.reset(new WebRTCIdentityService());
610 aec_dump_message_filter_ = new AecDumpMessageFilter(
611 GetIOMessageLoopProxy(), message_loop()->task_runner());
612 AddFilter(aec_dump_message_filter_.get());
614 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
615 p2p_socket_dispatcher_.get()));
616 #endif // defined(ENABLE_WEBRTC)
618 audio_input_message_filter_ =
619 new AudioInputMessageFilter(GetIOMessageLoopProxy());
620 AddFilter(audio_input_message_filter_.get());
622 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
623 AddFilter(audio_message_filter_.get());
625 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
626 AddFilter(midi_message_filter_.get());
628 bluetooth_message_filter_ = new BluetoothMessageFilter(thread_safe_sender());
629 AddFilter(bluetooth_message_filter_->GetFilter());
631 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
633 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
635 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
637 GetContentClient()->renderer()->RenderThreadStarted();
639 InitSkiaEventTracer();
640 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
641 skia::SkiaMemoryDumpProvider::GetInstance());
643 const base::CommandLine& command_line =
644 *base::CommandLine::ForCurrentProcess();
646 cc::LayerSettings layer_settings;
647 if (command_line.HasSwitch(switches::kEnableCompositorAnimationTimelines))
648 layer_settings.use_compositor_animation_timelines = true;
649 cc_blink::WebLayerImpl::SetLayerSettings(layer_settings);
651 is_threaded_animation_enabled_ =
652 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
654 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
655 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
657 #if defined(OS_MACOSX) && !defined(OS_IOS)
658 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
659 if (is_elastic_overscroll_enabled_) {
660 base::ScopedCFTypeRef<CFStringRef> key(
661 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
662 Boolean key_exists = false;
663 Boolean value = CFPreferencesGetAppBooleanValue(
664 key, kCFPreferencesCurrentApplication, &key_exists);
665 if (key_exists && !value)
666 is_elastic_overscroll_enabled_ = false;
668 #else
669 is_elastic_overscroll_enabled_ = false;
670 #endif
672 std::string image_texture_target_string =
673 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
674 StringToUintVector(image_texture_target_string, &use_image_texture_targets_);
676 if (command_line.HasSwitch(switches::kDisableLCDText)) {
677 is_lcd_text_enabled_ = false;
678 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
679 is_lcd_text_enabled_ = true;
680 } else {
681 #if defined(OS_ANDROID)
682 is_lcd_text_enabled_ = false;
683 #else
684 is_lcd_text_enabled_ = true;
685 #endif
688 is_gpu_rasterization_enabled_ =
689 command_line.HasSwitch(switches::kEnableGpuRasterization);
690 is_gpu_rasterization_forced_ =
691 command_line.HasSwitch(switches::kForceGpuRasterization);
693 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
694 std::string string_value = command_line.GetSwitchValueASCII(
695 switches::kGpuRasterizationMSAASampleCount);
696 bool parsed_msaa_sample_count =
697 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
698 DCHECK(parsed_msaa_sample_count) << string_value;
699 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
700 } else {
701 gpu_rasterization_msaa_sample_count_ = -1;
704 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
705 is_distance_field_text_enabled_ = false;
706 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
707 is_distance_field_text_enabled_ = true;
708 } else {
709 is_distance_field_text_enabled_ = false;
712 // Note that under Linux, the media library will normally already have
713 // been initialized by the Zygote before this instance became a Renderer.
714 media::InitializeMediaLibrary();
716 memory_pressure_listener_.reset(new base::MemoryPressureListener(
717 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
719 is_gather_pixel_refs_enabled_ = false;
721 int num_raster_threads = 0;
722 std::string string_value =
723 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
724 bool parsed_num_raster_threads =
725 base::StringToInt(string_value, &num_raster_threads);
726 DCHECK(parsed_num_raster_threads) << string_value;
727 DCHECK_GT(num_raster_threads, 0);
729 // Note: Currently, gathering of pixel refs when using a single
730 // raster thread doesn't provide any benefit. This might change
731 // in the future but we avoid it for now to reduce the cost of
732 // Picture::Create.
733 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
735 base::SimpleThread::Options thread_options;
736 #if defined(OS_ANDROID) || defined(OS_LINUX)
737 if (!command_line.HasSwitch(
738 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
739 thread_options.set_priority(base::ThreadPriority::BACKGROUND);
741 #endif
743 raster_worker_pool_->Start(num_raster_threads, thread_options);
745 // TODO(boliu): In single process, browser main loop should set up the
746 // discardable memory manager, and should skip this if kSingleProcess.
747 // See crbug.com/503724.
748 base::DiscardableMemoryAllocator::SetInstance(
749 ChildThreadImpl::discardable_shared_memory_manager());
751 service_registry()->AddService<RenderFrameSetup>(
752 base::Bind(CreateRenderFrameSetup));
753 service_registry()->AddService<EmbeddedWorkerSetup>(
754 base::Bind(CreateEmbeddedWorkerSetup));
756 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
759 RenderThreadImpl::~RenderThreadImpl() {
762 void RenderThreadImpl::Shutdown() {
763 FOR_EACH_OBSERVER(
764 RenderProcessObserver, observers_, OnRenderProcessShutdown());
766 ChildThreadImpl::Shutdown();
768 if (memory_observer_) {
769 message_loop()->RemoveTaskObserver(memory_observer_.get());
770 memory_observer_.reset();
773 // Wait for all databases to be closed.
774 if (blink_platform_impl_) {
775 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
776 // processing timer events while we're already in the process of shutting
777 // down blink, put a ScopePageLoadDeferrer on the stack.
778 WebView::willEnterModalLoop();
779 blink_platform_impl_->web_database_observer_impl()
780 ->WaitForAllDatabasesToClose();
781 WebView::didExitModalLoop();
784 // Shutdown in reverse of the initialization order.
785 if (devtools_agent_message_filter_.get()) {
786 RemoveFilter(devtools_agent_message_filter_.get());
787 devtools_agent_message_filter_ = NULL;
790 RemoveFilter(audio_input_message_filter_.get());
791 audio_input_message_filter_ = NULL;
793 #if defined(ENABLE_WEBRTC)
794 RTCPeerConnectionHandler::DestructAllHandlers();
795 // |peer_connection_factory_| cannot be deleted until after the main message
796 // loop has been destroyed. This is because there may be pending tasks that
797 // hold on to objects produced by the PC factory that depend on threads owned
798 // by the PC factory. Once those tasks have been freed, the factory can be
799 // deleted.
800 #endif
801 RemoveFilter(vc_manager_->video_capture_message_filter());
802 vc_manager_.reset();
804 RemoveFilter(db_message_filter_.get());
805 db_message_filter_ = NULL;
807 // Shutdown the file thread if it's running.
808 if (file_thread_)
809 file_thread_->Stop();
811 if (compositor_message_filter_.get()) {
812 RemoveFilter(compositor_message_filter_.get());
813 compositor_message_filter_ = NULL;
816 media_thread_.reset();
818 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
819 RemoveFilter(audio_message_filter_.get());
820 audio_message_filter_ = NULL;
822 compositor_thread_.reset();
824 raster_worker_pool_->Shutdown();
826 main_input_callback_.Cancel();
827 input_handler_manager_.reset();
828 if (input_event_filter_.get()) {
829 RemoveFilter(input_event_filter_.get());
830 input_event_filter_ = NULL;
833 // RemoveEmbeddedWorkerRoute may be called while deleting
834 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
835 // RenderThreadImpl.
836 embedded_worker_dispatcher_.reset();
838 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
839 // hold pointers to V8 objects (e.g., via pending requests).
840 main_thread_indexed_db_dispatcher_.reset();
842 main_thread_compositor_task_runner_ = NULL;
844 // Context providers must be released prior to destroying the GPU channel.
845 gpu_va_context_provider_ = nullptr;
846 shared_main_thread_contexts_ = nullptr;
848 if (gpu_channel_.get())
849 gpu_channel_->DestroyChannel();
851 // TODO(port)
852 #if defined(OS_WIN)
853 // Clean up plugin channels before this thread goes away.
854 NPChannelBase::CleanupChannels();
855 #endif
857 // Shut down the message loop and the renderer scheduler before shutting down
858 // Blink. This prevents a scenario where a pending task in the message loop
859 // accesses Blink objects after Blink shuts down.
860 // This must be at the very end of the shutdown sequence. You must not touch
861 // the message loop after this.
862 renderer_scheduler_->Shutdown();
863 main_message_loop_.reset();
864 if (blink_platform_impl_)
865 blink::shutdown();
867 lazy_tls.Pointer()->Set(NULL);
870 bool RenderThreadImpl::Send(IPC::Message* msg) {
871 // Certain synchronous messages cannot always be processed synchronously by
872 // the browser, e.g., putting up UI and waiting for the user. This could cause
873 // a complete hang of Chrome if a windowed plugin is trying to communicate
874 // with the renderer thread since the browser's UI thread could be stuck
875 // (within a Windows API call) trying to synchronously communicate with the
876 // plugin. The remedy is to pump messages on this thread while the browser
877 // is processing this request. This creates an opportunity for re-entrancy
878 // into WebKit, so we need to take care to disable callbacks, timers, and
879 // pending network loads that could trigger such callbacks.
880 bool pumping_events = false;
881 if (msg->is_sync()) {
882 if (msg->is_caller_pumping_messages()) {
883 pumping_events = true;
887 bool notify_webkit_of_modal_loop = true; // default value
888 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
890 #if defined(ENABLE_PLUGINS)
891 int render_view_id = MSG_ROUTING_NONE;
892 #endif
894 if (pumping_events) {
895 renderer_scheduler_->SuspendTimerQueue();
897 if (notify_webkit_of_modal_loop)
898 WebView::willEnterModalLoop();
899 #if defined(ENABLE_PLUGINS)
900 RenderViewImpl* render_view =
901 RenderViewImpl::FromRoutingID(msg->routing_id());
902 if (render_view) {
903 render_view_id = msg->routing_id();
904 PluginChannelHost::Broadcast(
905 new PluginMsg_SignalModalDialogEvent(render_view_id));
907 #endif
910 bool rv = ChildThreadImpl::Send(msg);
912 if (pumping_events) {
913 #if defined(ENABLE_PLUGINS)
914 if (render_view_id != MSG_ROUTING_NONE) {
915 PluginChannelHost::Broadcast(
916 new PluginMsg_ResetModalDialogEvent(render_view_id));
918 #endif
920 if (notify_webkit_of_modal_loop)
921 WebView::didExitModalLoop();
923 renderer_scheduler_->ResumeTimerQueue();
926 return rv;
929 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
930 return channel();
933 std::string RenderThreadImpl::GetLocale() {
934 // The browser process should have passed the locale to the renderer via the
935 // --lang command line flag.
936 const base::CommandLine& parsed_command_line =
937 *base::CommandLine::ForCurrentProcess();
938 const std::string& lang =
939 parsed_command_line.GetSwitchValueASCII(switches::kLang);
940 DCHECK(!lang.empty());
941 return lang;
944 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
945 return sync_message_filter();
948 scoped_refptr<base::SingleThreadTaskRunner>
949 RenderThreadImpl::GetIOMessageLoopProxy() {
950 return ChildProcess::current()->io_task_runner();
953 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
954 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
955 PendingRenderFrameConnectMap::iterator it =
956 pending_render_frame_connects_.find(routing_id);
957 if (it == pending_render_frame_connects_.end())
958 return;
960 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
961 if (!frame)
962 return;
964 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
965 mojo::InterfaceRequest<mojo::ServiceProvider> services(
966 connection->services().Pass());
967 mojo::ServiceProviderPtr exposed_services(
968 connection->exposed_services().Pass());
969 exposed_services.set_connection_error_handler(mojo::Closure());
970 pending_render_frame_connects_.erase(it);
972 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
975 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
976 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
979 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
980 IPC::Listener* listener) {
981 AddRoute(routing_id, listener);
982 if (devtools_agent_message_filter_.get()) {
983 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
984 routing_id);
988 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
989 RemoveRoute(routing_id);
990 if (devtools_agent_message_filter_.get()) {
991 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
992 routing_id);
996 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
997 int routing_id,
998 mojo::InterfaceRequest<mojo::ServiceProvider> services,
999 mojo::ServiceProviderPtr exposed_services) {
1000 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
1001 pending_render_frame_connects_.insert(std::make_pair(
1002 routing_id,
1003 make_scoped_refptr(new PendingRenderFrameConnect(
1004 routing_id, services.Pass(), exposed_services.Pass()))));
1005 CHECK(result.second) << "Inserting a duplicate item.";
1008 int RenderThreadImpl::GenerateRoutingID() {
1009 int routing_id = MSG_ROUTING_NONE;
1010 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
1011 return routing_id;
1014 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
1015 channel()->AddFilter(filter);
1018 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
1019 channel()->RemoveFilter(filter);
1022 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
1023 observers_.AddObserver(observer);
1026 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
1027 observers_.RemoveObserver(observer);
1030 void RenderThreadImpl::SetResourceDispatcherDelegate(
1031 ResourceDispatcherDelegate* delegate) {
1032 resource_dispatcher()->set_delegate(delegate);
1035 void RenderThreadImpl::SetResourceDispatchTaskQueue(
1036 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
1037 // Add a filter that forces resource messages to be dispatched via a
1038 // particular task runner.
1039 resource_scheduling_filter_ =
1040 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
1041 channel()->AddFilter(resource_scheduling_filter_.get());
1043 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1044 // same queue to ensure tasks are executed in the expected order.
1045 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1046 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1049 void RenderThreadImpl::EnsureWebKitInitialized() {
1050 if (blink_platform_impl_)
1051 return;
1053 const base::CommandLine& command_line =
1054 *base::CommandLine::ForCurrentProcess();
1056 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1057 if (command_line.HasSwitch(switches::kEnableVtune))
1058 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1059 #endif
1061 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1063 blink_platform_impl_.reset(
1064 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1065 blink::initialize(blink_platform_impl_.get());
1067 v8::Isolate* isolate = blink::mainThreadIsolate();
1068 isolate->SetCreateHistogramFunction(CreateHistogram);
1069 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1071 main_thread_compositor_task_runner_ =
1072 renderer_scheduler_->CompositorTaskRunner();
1074 main_input_callback_.Reset(
1075 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1076 base::Unretained(this)));
1078 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1080 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1081 if (enable) {
1082 #if defined(OS_ANDROID)
1083 if (SynchronousCompositorFactory* factory =
1084 SynchronousCompositorFactory::GetInstance())
1085 compositor_task_runner_ = factory->GetCompositorTaskRunner();
1086 #endif
1087 if (!compositor_task_runner_.get()) {
1088 compositor_thread_.reset(new base::Thread("Compositor"));
1089 base::Thread::Options compositor_thread_options;
1090 #if defined(OS_ANDROID)
1091 compositor_thread_options.priority = base::ThreadPriority::DISPLAY;
1092 #endif
1093 compositor_thread_->StartWithOptions(compositor_thread_options);
1094 compositor_task_runner_ = compositor_thread_->task_runner();
1095 compositor_task_runner_->PostTask(
1096 FROM_HERE,
1097 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1098 false));
1101 InputHandlerManagerClient* input_handler_manager_client = NULL;
1102 #if defined(OS_ANDROID)
1103 if (SynchronousCompositorFactory* factory =
1104 SynchronousCompositorFactory::GetInstance()) {
1105 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1107 #endif
1108 if (!input_handler_manager_client) {
1109 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1110 new InputEventFilter(main_input_callback_.callback(),
1111 main_thread_compositor_task_runner_,
1112 compositor_task_runner_));
1113 input_handler_manager_client = compositor_input_event_filter.get();
1114 input_event_filter_ = compositor_input_event_filter;
1116 input_handler_manager_.reset(new InputHandlerManager(
1117 compositor_task_runner_, input_handler_manager_client,
1118 renderer_scheduler_.get()));
1121 if (!input_event_filter_.get()) {
1122 // Always provide an input event filter implementation to ensure consistent
1123 // input event scheduling and prioritization.
1124 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1125 // MainThreadInputEventFilter, crbug.com/436057.
1126 input_event_filter_ = new MainThreadInputEventFilter(
1127 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1129 AddFilter(input_event_filter_.get());
1131 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
1132 if (enable)
1133 compositor_impl_side_task_runner = compositor_task_runner_;
1134 else
1135 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
1137 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1138 compositor_impl_side_task_runner.get());
1139 AddFilter(compositor_message_filter_.get());
1141 RenderThreadImpl::RegisterSchemes();
1143 EnableBlinkPlatformLogChannels(
1144 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1146 RenderMediaClient::Initialize();
1148 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1150 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1151 AddFilter(devtools_agent_message_filter_.get());
1153 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1155 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1156 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1158 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1160 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1161 kImageCacheSingleAllocationByteLimit);
1163 // Hook up blink's codecs so skia can call them
1164 SkGraphics::SetImageGeneratorFromEncodedFactory(
1165 blink::WebImageGenerator::create);
1167 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1168 memory_observer_.reset(new MemoryObserver());
1169 message_loop()->AddTaskObserver(memory_observer_.get());
1172 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1173 std::string allowed_ports =
1174 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1175 net::SetExplicitlyAllowedPorts(allowed_ports);
1179 void RenderThreadImpl::RegisterSchemes() {
1180 // swappedout:
1181 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1182 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1183 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1185 // chrome:
1186 WebString chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme));
1187 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1188 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1189 chrome_scheme);
1190 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme);
1191 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme);
1193 // chrome-devtools:
1194 WebString devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme));
1195 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
1198 void RenderThreadImpl::NotifyTimezoneChange() {
1199 NotifyTimezoneChangeOnThisThread();
1200 RenderThread::Get()->PostTaskToAllWebWorkers(
1201 base::Bind(&NotifyTimezoneChangeOnThisThread));
1204 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1205 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1208 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1209 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1212 scoped_ptr<base::SharedMemory>
1213 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1214 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1217 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1218 return shared_bitmap_manager();
1221 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1222 EnsureWebKitInitialized();
1223 WebScriptController::registerExtension(extension);
1226 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1227 idle_notification_delay_in_ms_ = initial_delay_ms;
1228 idle_timer_.Stop();
1229 idle_timer_.Start(FROM_HERE,
1230 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1231 this, &RenderThreadImpl::IdleHandler);
1234 void RenderThreadImpl::IdleHandler() {
1235 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1236 GetContentClient()->renderer()->
1237 RunIdleHandlerWhenWidgetsHidden();
1238 if (run_in_foreground_tab) {
1239 if (idle_notifications_to_skip_ > 0) {
1240 --idle_notifications_to_skip_;
1241 } else {
1242 ReleaseFreeMemory();
1244 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1245 return;
1248 ReleaseFreeMemory();
1250 // Continue the idle timer if the webkit shared timer is not suspended or
1251 // something is left to do.
1252 bool continue_timer = !webkit_shared_timer_suspended_;
1254 if (blink::mainThreadIsolate() &&
1255 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1256 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1257 continue_timer = true;
1260 // Schedule next invocation. When the tab is originally hidden, an invocation
1261 // is scheduled for kInitialIdleHandlerDelayMs in
1262 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1263 // After that, idle calls can be much less frequent, so run at a maximum of
1264 // once every kLongIdleHandlerDelayMs.
1265 // Dampen the delay using the algorithm (if delay is in seconds):
1266 // delay = delay + 1 / (delay + 2)
1267 // Using floor(delay) has a dampening effect such as:
1268 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1269 // If the delay is in milliseconds, the above formula is equivalent to:
1270 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1271 // which is equivalent to
1272 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1273 if (continue_timer) {
1274 ScheduleIdleHandler(
1275 std::max(kLongIdleHandlerDelayMs,
1276 idle_notification_delay_in_ms_ +
1277 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1279 } else {
1280 idle_timer_.Stop();
1283 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1286 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1287 return idle_notification_delay_in_ms_;
1290 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1291 int64 idle_notification_delay_in_ms) {
1292 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1295 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1296 child_histogram_message_filter()->SendHistograms(sequence_number);
1299 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1300 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1303 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1304 bool result = false;
1305 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1306 return result;
1309 void RenderThreadImpl::PostponeIdleNotification() {
1310 idle_notifications_to_skip_ = 2;
1313 scoped_refptr<media::GpuVideoAcceleratorFactories>
1314 RenderThreadImpl::GetGpuFactories() {
1315 DCHECK(IsMainThread());
1317 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1319 #if defined(OS_ANDROID)
1320 if (SynchronousCompositorFactory::GetInstance()) {
1321 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1322 DLOG(WARNING) << "Accelerated video decoding is not explicitly disabled, "
1323 "but is not supported by in-process rendering";
1325 return NULL;
1327 #endif
1329 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1330 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1331 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1332 GetMediaThreadTaskRunner();
1333 if (!gpu_va_context_provider_.get() ||
1334 gpu_va_context_provider_->DestroyedOnMainThread()) {
1335 if (!gpu_channel_host.get()) {
1336 gpu_channel_host = EstablishGpuChannelSync(
1337 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1339 blink::WebGraphicsContext3D::Attributes attributes;
1340 bool lose_context_when_out_of_memory = false;
1341 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1342 make_scoped_ptr(
1343 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1344 gpu_channel_host.get(), attributes,
1345 lose_context_when_out_of_memory,
1346 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1347 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1348 NULL)),
1349 GPU_VIDEO_ACCELERATOR_CONTEXT);
1351 if (gpu_va_context_provider_.get()) {
1352 bool enable_video_accelerator =
1353 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1354 std::string image_texture_target_string =
1355 cmd_line->GetSwitchValueASCII(switches::kVideoImageTextureTarget);
1356 unsigned image_texture_target = 0;
1357 bool parsed_image_texture_target =
1358 base::StringToUint(image_texture_target_string, &image_texture_target);
1359 DCHECK(parsed_image_texture_target);
1360 CHECK(gpu_channel_.get()) << "Have gpu_va_context_provider but no "
1361 "gpu_channel_. See crbug.com/495185.";
1362 CHECK(gpu_channel_host.get()) << "Have gpu_va_context_provider but lost "
1363 "gpu_channel_. See crbug.com/495185.";
1364 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1365 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_,
1366 image_texture_target, enable_video_accelerator);
1368 return gpu_factories;
1371 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1372 RenderThreadImpl::CreateOffscreenContext3d() {
1373 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1374 bool lose_context_when_out_of_memory = true;
1376 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1377 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1378 return make_scoped_ptr(
1379 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1380 gpu_channel_host.get(),
1381 attributes,
1382 lose_context_when_out_of_memory,
1383 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1384 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1385 NULL));
1388 scoped_refptr<cc_blink::ContextProviderWebContext>
1389 RenderThreadImpl::SharedMainThreadContextProvider() {
1390 DCHECK(IsMainThread());
1391 if (!shared_main_thread_contexts_.get() ||
1392 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1393 shared_main_thread_contexts_ = NULL;
1394 #if defined(OS_ANDROID)
1395 SynchronousCompositorFactory* factory =
1396 SynchronousCompositorFactory::GetInstance();
1397 if (factory && factory->OverrideWithFactory()) {
1398 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1399 GetOffscreenAttribs(), "Offscreen-MainThread");
1401 #endif
1402 if (!shared_main_thread_contexts_.get()) {
1403 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1404 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT);
1406 if (shared_main_thread_contexts_.get() &&
1407 !shared_main_thread_contexts_->BindToCurrentThread())
1408 shared_main_thread_contexts_ = NULL;
1410 return shared_main_thread_contexts_;
1413 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1414 if (!audio_renderer_mixer_manager_) {
1415 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1416 GetAudioHardwareConfig()));
1419 return audio_renderer_mixer_manager_.get();
1422 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1423 if (!audio_hardware_config_) {
1424 media::AudioParameters input_params;
1425 media::AudioParameters output_params;
1426 Send(new ViewHostMsg_GetAudioHardwareConfig(
1427 &input_params, &output_params));
1429 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1430 input_params, output_params));
1433 return audio_hardware_config_.get();
1436 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1437 return ChildProcess::current()->GetShutDownEvent();
1440 #if defined(OS_WIN)
1441 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1442 const base::string16& str) {
1443 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1446 #endif // OS_WIN
1448 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1449 return service_registry();
1452 bool RenderThreadImpl::IsGpuRasterizationForced() {
1453 return is_gpu_rasterization_forced_;
1456 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1457 return is_gpu_rasterization_enabled_;
1460 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1461 return gpu_rasterization_msaa_sample_count_;
1464 bool RenderThreadImpl::IsLcdTextEnabled() {
1465 return is_lcd_text_enabled_;
1468 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1469 return is_distance_field_text_enabled_;
1472 bool RenderThreadImpl::IsZeroCopyEnabled() {
1473 return is_zero_copy_enabled_;
1476 bool RenderThreadImpl::IsOneCopyEnabled() {
1477 return is_one_copy_enabled_;
1480 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1481 return is_elastic_overscroll_enabled_;
1484 std::vector<unsigned> RenderThreadImpl::GetImageTextureTargets() {
1485 return use_image_texture_targets_;
1488 scoped_refptr<base::SingleThreadTaskRunner>
1489 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1490 return main_thread_compositor_task_runner_;
1493 scoped_refptr<base::SingleThreadTaskRunner>
1494 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1495 return compositor_task_runner_;
1498 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1499 return gpu_memory_buffer_manager();
1502 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1503 return renderer_scheduler_.get();
1506 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1507 return SharedMainThreadContextProvider().get();
1510 scoped_ptr<cc::BeginFrameSource>
1511 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1512 #if defined(OS_ANDROID)
1513 if (SynchronousCompositorFactory* factory =
1514 SynchronousCompositorFactory::GetInstance()) {
1515 return factory->CreateExternalBeginFrameSource(routing_id);
1517 #endif
1518 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1519 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1522 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1523 return raster_worker_pool_->GetTaskGraphRunner();
1526 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1527 return is_gather_pixel_refs_enabled_;
1530 bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1531 return is_threaded_animation_enabled_;
1534 bool RenderThreadImpl::IsMainThread() {
1535 return !!current();
1538 scoped_refptr<base::SingleThreadTaskRunner>
1539 RenderThreadImpl::GetIOThreadTaskRunner() {
1540 return io_thread_task_runner_;
1543 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1544 size_t size) {
1545 return scoped_ptr<base::SharedMemory>(
1546 HostAllocateSharedMemoryBuffer(size));
1549 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1550 int32 surface_id,
1551 const GPUCreateCommandBufferConfig& init_params,
1552 int32 route_id) {
1553 TRACE_EVENT1("gpu",
1554 "RenderThreadImpl::CreateViewCommandBuffer",
1555 "surface_id",
1556 surface_id);
1558 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1559 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1560 surface_id,
1561 init_params,
1562 route_id,
1563 &result);
1565 // Allow calling this from the compositor thread.
1566 thread_safe_sender()->Send(message);
1568 return result;
1571 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1572 notify_webkit_of_modal_loop_ = false;
1575 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1576 base::ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1577 RenderProcessObserver* observer;
1578 while ((observer = it.GetNext()) != NULL) {
1579 if (observer->OnControlMessageReceived(msg))
1580 return true;
1583 // Some messages are handled by delegates.
1584 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1585 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1586 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1587 return true;
1590 bool handled = true;
1591 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1592 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1593 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1594 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1595 OnSetZoomLevelForCurrentURL)
1596 // TODO(port): removed from render_messages_internal.h;
1597 // is there a new non-windows message I should add here?
1598 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1599 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1600 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1601 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1602 #if defined(OS_ANDROID)
1603 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1604 OnSetWebKitSharedTimersSuspended)
1605 #endif
1606 #if defined(OS_MACOSX)
1607 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1608 #endif
1609 #if defined(ENABLE_PLUGINS)
1610 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1611 #endif
1612 IPC_MESSAGE_UNHANDLED(handled = false)
1613 IPC_END_MESSAGE_MAP()
1614 return handled;
1617 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params) {
1618 CompositorDependencies* compositor_deps = this;
1619 RenderFrameImpl::CreateFrame(
1620 params.routing_id, params.parent_routing_id,
1621 params.previous_sibling_routing_id, params.proxy_routing_id,
1622 params.replication_state, compositor_deps, params.widget_params);
1625 void RenderThreadImpl::OnCreateNewFrameProxy(
1626 int routing_id,
1627 int parent_routing_id,
1628 int render_view_routing_id,
1629 const FrameReplicationState& replicated_state) {
1630 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1631 render_view_routing_id, replicated_state);
1634 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1635 const std::string& host,
1636 double zoom_level) {
1637 RenderViewZoomer zoomer(scheme, host, zoom_level);
1638 RenderView::ForEach(&zoomer);
1641 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1642 EnsureWebKitInitialized();
1643 CompositorDependencies* compositor_deps = this;
1644 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1645 RenderViewImpl::Create(compositor_deps, params, false);
1648 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1649 CauseForGpuLaunch cause_for_gpu_launch) {
1650 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1652 if (gpu_channel_.get()) {
1653 // Do nothing if we already have a GPU channel or are already
1654 // establishing one.
1655 if (!gpu_channel_->IsLost())
1656 return gpu_channel_.get();
1658 // Recreate the channel if it has been lost.
1659 gpu_channel_->DestroyChannel();
1660 gpu_channel_ = NULL;
1663 // Ask the browser for the channel name.
1664 int client_id = 0;
1665 IPC::ChannelHandle channel_handle;
1666 gpu::GPUInfo gpu_info;
1667 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1668 &client_id,
1669 &channel_handle,
1670 &gpu_info)) ||
1671 #if defined(OS_POSIX)
1672 channel_handle.socket.fd == -1 ||
1673 #endif
1674 channel_handle.name.empty()) {
1675 // Otherwise cancel the connection.
1676 return NULL;
1679 GetContentClient()->SetGpuInfo(gpu_info);
1681 // Cache some variables that are needed on the compositor thread for our
1682 // implementation of GpuChannelHostFactory.
1683 io_thread_task_runner_ = ChildProcess::current()->io_task_runner();
1685 gpu_channel_ =
1686 GpuChannelHost::Create(this,
1687 gpu_info,
1688 channel_handle,
1689 ChildProcess::current()->GetShutDownEvent(),
1690 gpu_memory_buffer_manager());
1691 return gpu_channel_.get();
1694 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1695 blink::WebMediaStreamCenterClient* client) {
1696 #if defined(OS_ANDROID)
1697 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1698 switches::kDisableWebRTC))
1699 return NULL;
1700 #endif
1702 #if defined(ENABLE_WEBRTC)
1703 if (!media_stream_center_) {
1704 media_stream_center_ = GetContentClient()->renderer()
1705 ->OverrideCreateWebMediaStreamCenter(client);
1706 if (!media_stream_center_) {
1707 scoped_ptr<MediaStreamCenter> media_stream_center(
1708 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1709 media_stream_center_ = media_stream_center.release();
1712 #endif
1713 return media_stream_center_;
1716 #if defined(ENABLE_WEBRTC)
1717 PeerConnectionDependencyFactory*
1718 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1719 return peer_connection_factory_.get();
1721 #endif
1723 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1724 if (!gpu_channel_.get())
1725 return NULL;
1727 if (gpu_channel_->IsLost())
1728 return NULL;
1730 return gpu_channel_.get();
1733 #if defined(ENABLE_PLUGINS)
1734 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1735 EnsureWebKitInitialized();
1736 // The call below will cause a GetPlugins call with refresh=true, but at this
1737 // point we already know that the browser has refreshed its list, so disable
1738 // refresh temporarily to prevent each renderer process causing the list to be
1739 // regenerated.
1740 blink_platform_impl_->set_plugin_refresh_allowed(false);
1741 blink::resetPluginCache(reload_pages);
1742 blink_platform_impl_->set_plugin_refresh_allowed(true);
1744 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1746 #endif
1748 void RenderThreadImpl::OnNetworkTypeChanged(
1749 net::NetworkChangeNotifier::ConnectionType type) {
1750 EnsureWebKitInitialized();
1751 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1752 WebNetworkStateNotifier::setOnLine(online);
1753 FOR_EACH_OBSERVER(
1754 RenderProcessObserver, observers_, NetworkStateChanged(online));
1755 WebNetworkStateNotifier::setWebConnectionType(
1756 NetConnectionTypeToWebConnectionType(type));
1759 void RenderThreadImpl::OnUpdateTimezone(const std::string& zone_id) {
1760 if (!blink_platform_impl_)
1761 return;
1762 if (!zone_id.empty()) {
1763 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
1764 icu::UnicodeString::fromUTF8(zone_id));
1765 icu::TimeZone::adoptDefault(new_zone);
1766 VLOG(1) << "ICU default timezone is set to " << zone_id;
1768 NotifyTimezoneChange();
1771 #if defined(OS_ANDROID)
1772 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1773 EnsureWebKitInitialized();
1774 if (suspend) {
1775 renderer_scheduler_->SuspendTimerQueue();
1776 } else {
1777 renderer_scheduler_->ResumeTimerQueue();
1779 webkit_shared_timer_suspended_ = suspend;
1781 #endif
1783 #if defined(OS_MACOSX)
1784 void RenderThreadImpl::OnUpdateScrollbarTheme(
1785 const ViewMsg_UpdateScrollbarTheme_Params& params) {
1786 EnsureWebKitInitialized();
1787 static_cast<WebScrollbarBehaviorImpl*>(
1788 blink_platform_impl_->scrollbarBehavior())
1789 ->set_jump_on_track_click(params.jump_on_track_click);
1791 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
1792 params.initial_button_delay, params.autoscroll_button_delay,
1793 params.preferred_scroller_style, params.redraw,
1794 params.scroll_animation_enabled, params.button_placement);
1796 #endif
1798 void RenderThreadImpl::OnCreateNewSharedWorker(
1799 const WorkerProcessMsg_CreateWorker_Params& params) {
1800 // EmbeddedSharedWorkerStub will self-destruct.
1801 new EmbeddedSharedWorkerStub(params.url,
1802 params.name,
1803 params.content_security_policy,
1804 params.security_policy_type,
1805 params.pause_on_start,
1806 params.route_id);
1809 void RenderThreadImpl::OnMemoryPressure(
1810 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1811 ReleaseFreeMemory();
1813 // Do not call into blink if it is not initialized.
1814 if (blink_platform_impl_) {
1815 blink::WebCache::pruneAll();
1817 if (blink::mainThreadIsolate()) {
1818 // Trigger full v8 garbage collection on memory pressure notifications.
1819 // This will potentially hang the renderer for a long time, however, when
1820 // we receive a memory pressure notification, we might be about to be
1821 // killed.
1822 blink::mainThreadIsolate()->LowMemoryNotification();
1823 RenderThread::Get()->PostTaskToAllWebWorkers(
1824 base::Bind(&LowMemoryNotificationOnThisThread));
1827 if (memory_pressure_level ==
1828 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1829 // Clear the image cache.
1830 blink::WebImageCache::clear();
1832 // Purge Skia font cache, by setting it to 0 and then again to the
1833 // previous limit.
1834 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1835 SkGraphics::SetFontCacheLimit(font_cache_limit);
1840 scoped_refptr<base::SingleThreadTaskRunner>
1841 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1842 DCHECK(message_loop() == base::MessageLoop::current());
1843 if (!file_thread_) {
1844 file_thread_.reset(new base::Thread("Renderer::FILE"));
1845 file_thread_->Start();
1847 return file_thread_->task_runner();
1850 scoped_refptr<base::SingleThreadTaskRunner>
1851 RenderThreadImpl::GetMediaThreadTaskRunner() {
1852 DCHECK(message_loop() == base::MessageLoop::current());
1853 if (!media_thread_) {
1854 media_thread_.reset(new base::Thread("Media"));
1855 media_thread_->Start();
1857 #if defined(OS_ANDROID)
1858 renderer_demuxer_ = new RendererDemuxerAndroid();
1859 AddFilter(renderer_demuxer_.get());
1860 #endif
1862 return media_thread_->task_runner();
1865 base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
1866 return raster_worker_pool_.get();
1869 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1870 blink_platform_impl_->sampleGamepads(*data);
1873 bool RenderThreadImpl::RendererIsHidden() const {
1874 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1877 void RenderThreadImpl::WidgetCreated() {
1878 bool renderer_was_hidden = RendererIsHidden();
1879 widget_count_++;
1880 if (renderer_was_hidden)
1881 OnRendererVisible();
1884 void RenderThreadImpl::WidgetDestroyed() {
1885 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1886 // unhidden before WidgetDestroyed is called.
1887 DCHECK_GT(widget_count_, 0);
1888 DCHECK_GT(widget_count_, hidden_widget_count_);
1889 widget_count_--;
1890 if (RendererIsHidden())
1891 OnRendererHidden();
1894 void RenderThreadImpl::WidgetHidden() {
1895 DCHECK_LT(hidden_widget_count_, widget_count_);
1896 hidden_widget_count_++;
1897 if (RendererIsHidden())
1898 OnRendererHidden();
1901 void RenderThreadImpl::WidgetRestored() {
1902 bool renderer_was_hidden = RendererIsHidden();
1903 DCHECK_GT(hidden_widget_count_, 0);
1904 hidden_widget_count_--;
1905 if (renderer_was_hidden)
1906 OnRendererVisible();
1909 void RenderThreadImpl::OnRendererHidden() {
1910 renderer_scheduler_->OnRendererHidden();
1912 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1913 // scheduled by the RendererScheduler - http://crbug.com/469210.
1914 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1915 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1918 void RenderThreadImpl::OnRendererVisible() {
1919 renderer_scheduler_->OnRendererVisible();
1921 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1922 return;
1924 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1927 void RenderThreadImpl::ReleaseFreeMemory() {
1928 base::allocator::ReleaseFreeMemory();
1929 discardable_shared_memory_manager()->ReleaseFreeMemory();
1931 if (blink_platform_impl_)
1932 blink::decommitFreeableMemory();
1935 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1936 int routing_id,
1937 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1938 mojo::ServiceProviderPtr exposed_services)
1939 : routing_id_(routing_id),
1940 services_(services.Pass()),
1941 exposed_services_(exposed_services.Pass()) {
1942 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1943 // is received. In that case, the RenderFrameHost should close the connection,
1944 // which is detected by setting an error handler on |exposed_services_|.
1945 exposed_services_.set_connection_error_handler(base::Bind(
1946 &RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError,
1947 base::Unretained(this)));
1950 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1953 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1954 size_t erased =
1955 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1956 routing_id_);
1957 DCHECK_EQ(1u, erased);
1960 } // namespace content