Add ICU message format support
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blobf619f8456ba4cec19428e93daa6cea289596ef76
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 // Remote frames don't host documents.
244 // TODO(wjmaclean) Although it seems likely that a frame without a
245 // document can safely early-out here, we should confirm this is truly
246 // the case. https://crbug.com/477007
247 if (webview->mainFrame()->isWebRemoteFrame())
248 return true;
250 WebDocument document = webview->mainFrame()->document();
252 // Don't set zoom level for full-page plugin since they don't use the same
253 // zoom settings.
254 if (document.isPluginDocument())
255 return true;
256 GURL url(document.url());
257 // Empty scheme works as wildcard that matches any scheme,
258 if ((net::GetHostOrSpecFromURL(url) == host_) &&
259 (scheme_.empty() || scheme_ == url.scheme()) &&
260 !static_cast<RenderViewImpl*>(render_view)
261 ->uses_temporary_zoom_level()) {
262 webview->hidePopups();
263 webview->setZoomLevel(zoom_level_);
265 return true;
268 private:
269 const std::string scheme_;
270 const std::string host_;
271 const double zoom_level_;
273 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
276 std::string HostToCustomHistogramSuffix(const std::string& host) {
277 if (host == "mail.google.com")
278 return ".gmail";
279 if (host == "docs.google.com" || host == "drive.google.com")
280 return ".docs";
281 if (host == "plus.google.com")
282 return ".plus";
283 if (host == "inbox.google.com")
284 return ".inbox";
285 return std::string();
288 void* CreateHistogram(
289 const char *name, int min, int max, size_t buckets) {
290 if (min <= 0)
291 min = 1;
292 std::string histogram_name;
293 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
294 if (render_thread_impl) { // Can be null in tests.
295 histogram_name = render_thread_impl->
296 histogram_customizer()->ConvertToCustomHistogramName(name);
297 } else {
298 histogram_name = std::string(name);
300 base::HistogramBase* histogram = base::Histogram::FactoryGet(
301 histogram_name, min, max, buckets,
302 base::Histogram::kUmaTargetedHistogramFlag);
303 return histogram;
306 void AddHistogramSample(void* hist, int sample) {
307 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
308 histogram->Add(sample);
311 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
312 const gfx::Size& size) {
313 return ChildThreadImpl::current()->shared_bitmap_manager()->
314 AllocateSharedBitmap(size);
317 void EnableBlinkPlatformLogChannels(const std::string& channels) {
318 if (channels.empty())
319 return;
320 base::StringTokenizer t(channels, ", ");
321 while (t.GetNext())
322 blink::enableLogChannel(t.token().c_str());
325 void NotifyTimezoneChangeOnThisThread() {
326 v8::Isolate* isolate = v8::Isolate::GetCurrent();
327 if (!isolate)
328 return;
329 v8::Date::DateTimeConfigurationChangeNotification(isolate);
332 void LowMemoryNotificationOnThisThread() {
333 v8::Isolate* isolate = v8::Isolate::GetCurrent();
334 if (!isolate)
335 return;
336 isolate->LowMemoryNotification();
339 class RenderFrameSetupImpl : public RenderFrameSetup {
340 public:
341 explicit RenderFrameSetupImpl(
342 mojo::InterfaceRequest<RenderFrameSetup> request)
343 : routing_id_highmark_(-1), binding_(this, request.Pass()) {}
345 void ExchangeServiceProviders(
346 int32_t frame_routing_id,
347 mojo::InterfaceRequest<mojo::ServiceProvider> services,
348 mojo::ServiceProviderPtr exposed_services)
349 override {
350 // TODO(morrita): This is for investigating http://crbug.com/415059 and
351 // should be removed once it is fixed.
352 CHECK_LT(routing_id_highmark_, frame_routing_id);
353 routing_id_highmark_ = frame_routing_id;
355 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
356 // We can receive a GetServiceProviderForFrame message for a frame not yet
357 // created due to a race between the message and a ViewMsg_New IPC that
358 // triggers creation of the RenderFrame we want.
359 if (!frame) {
360 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
361 frame_routing_id, services.Pass(), exposed_services.Pass());
362 return;
365 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
368 private:
369 int32_t routing_id_highmark_;
370 mojo::StrongBinding<RenderFrameSetup> binding_;
373 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
374 new RenderFrameSetupImpl(request.Pass());
377 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
378 blink::WebGraphicsContext3D::Attributes attributes;
379 attributes.shareResources = true;
380 attributes.depth = false;
381 attributes.stencil = false;
382 attributes.antialias = false;
383 attributes.noAutomaticFlushes = true;
384 return attributes;
387 void SetupEmbeddedWorkerOnWorkerThread(
388 mojo::InterfaceRequest<mojo::ServiceProvider> services,
389 mojo::ServiceProviderPtr exposed_services) {
390 ServiceWorkerContextClient* client =
391 ServiceWorkerContextClient::ThreadSpecificInstance();
392 // It is possible for client to be null if for some reason the worker died
393 // before this call made it to the worker thread. In that case just do
394 // nothing and let mojo close the connection.
395 if (!client)
396 return;
397 client->BindServiceRegistry(services.Pass(), exposed_services.Pass());
400 class EmbeddedWorkerSetupImpl : public EmbeddedWorkerSetup {
401 public:
402 explicit EmbeddedWorkerSetupImpl(
403 mojo::InterfaceRequest<EmbeddedWorkerSetup> request)
404 : binding_(this, request.Pass()) {}
406 void ExchangeServiceProviders(
407 int32_t thread_id,
408 mojo::InterfaceRequest<mojo::ServiceProvider> services,
409 mojo::ServiceProviderPtr exposed_services) override {
410 WorkerTaskRunner::Instance()->GetTaskRunnerFor(thread_id)->PostTask(
411 FROM_HERE,
412 base::Bind(&SetupEmbeddedWorkerOnWorkerThread, base::Passed(&services),
413 base::Passed(&exposed_services)));
416 private:
417 mojo::StrongBinding<EmbeddedWorkerSetup> binding_;
420 void CreateEmbeddedWorkerSetup(
421 mojo::InterfaceRequest<EmbeddedWorkerSetup> request) {
422 new EmbeddedWorkerSetupImpl(request.Pass());
425 } // namespace
427 // For measuring memory usage after each task. Behind a command line flag.
428 class MemoryObserver : public base::MessageLoop::TaskObserver {
429 public:
430 MemoryObserver() {}
431 ~MemoryObserver() override {}
433 void WillProcessTask(const base::PendingTask& pending_task) override {}
435 void DidProcessTask(const base::PendingTask& pending_task) override {
436 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
439 private:
440 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
443 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
444 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
445 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
446 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
449 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
451 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
452 const std::string& host, size_t view_count) {
453 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
454 switches::kDisableHistogramCustomizer)) {
455 return;
457 // Check if all RenderViews are displaying a page from the same host. If there
458 // is only one RenderView, the common host is this view's host. If there are
459 // many, check if this one shares the common host of the other
460 // RenderViews. It's ok to not detect some cases where the RenderViews share a
461 // common host. This information is only used for producing custom histograms.
462 if (view_count == 1)
463 SetCommonHost(host);
464 else if (host != common_host_)
465 SetCommonHost(std::string());
468 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
469 const char* histogram_name) const {
470 std::string name(histogram_name);
471 if (!common_host_histogram_suffix_.empty() &&
472 custom_histograms_.find(name) != custom_histograms_.end())
473 name += common_host_histogram_suffix_;
474 return name;
477 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
478 const std::string& host) {
479 if (host != common_host_) {
480 common_host_ = host;
481 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
482 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
486 // static
487 RenderThreadImpl* RenderThreadImpl::Create(
488 const InProcessChildThreadParams& params) {
489 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler =
490 scheduler::RendererScheduler::Create();
491 return new RenderThreadImpl(params, renderer_scheduler.Pass());
494 // static
495 RenderThreadImpl* RenderThreadImpl::Create(
496 scoped_ptr<base::MessageLoop> main_message_loop,
497 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler) {
498 return new RenderThreadImpl(main_message_loop.Pass(),
499 renderer_scheduler.Pass());
502 RenderThreadImpl* RenderThreadImpl::current() {
503 return lazy_tls.Pointer()->Get();
506 RenderThreadImpl::RenderThreadImpl(
507 const InProcessChildThreadParams& params,
508 scoped_ptr<scheduler::RendererScheduler> scheduler)
509 : ChildThreadImpl(Options::Builder()
510 .InBrowserProcess(params)
511 .UseMojoChannel(ShouldUseMojoChannel())
512 .Build()),
513 renderer_scheduler_(scheduler.Pass()),
514 raster_worker_pool_(new RasterWorkerPool()) {
515 Init();
518 // When we run plugins in process, we actually run them on the render thread,
519 // which means that we need to make the render thread pump UI events.
520 RenderThreadImpl::RenderThreadImpl(
521 scoped_ptr<base::MessageLoop> main_message_loop,
522 scoped_ptr<scheduler::RendererScheduler> scheduler)
523 : ChildThreadImpl(Options::Builder()
524 .UseMojoChannel(ShouldUseMojoChannel())
525 .Build()),
526 renderer_scheduler_(scheduler.Pass()),
527 main_message_loop_(main_message_loop.Pass()),
528 raster_worker_pool_(new RasterWorkerPool()) {
529 Init();
532 void RenderThreadImpl::Init() {
533 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
535 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
536 base::PlatformThread::CurrentId(),
537 kTraceEventRendererMainThreadSortIndex);
539 #if defined(OS_MACOSX) || defined(OS_ANDROID)
540 // On Mac and Android, the select popups are rendered by the browser.
541 blink::WebView::setUseExternalPopupMenus(true);
542 #endif
544 lazy_tls.Pointer()->Set(this);
546 // Register this object as the main thread.
547 ChildProcess::current()->set_main_thread(this);
549 // In single process the single process is all there is.
550 notify_webkit_of_modal_loop_ = true;
551 webkit_shared_timer_suspended_ = false;
552 widget_count_ = 0;
553 hidden_widget_count_ = 0;
554 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
555 idle_notifications_to_skip_ = 0;
556 layout_test_mode_ = false;
558 appcache_dispatcher_.reset(
559 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
560 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
561 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
562 thread_safe_sender()));
563 main_thread_cache_storage_dispatcher_.reset(
564 new CacheStorageDispatcher(thread_safe_sender()));
565 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
567 // Note: This may reorder messages from the ResourceDispatcher with respect to
568 // other subsystems.
569 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
570 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
571 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
572 kMaxResourceRequestsPerFlushWhenThrottled));
573 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
575 media_stream_center_ = NULL;
577 db_message_filter_ = new DBMessageFilter();
578 AddFilter(db_message_filter_.get());
580 vc_manager_.reset(new VideoCaptureImplManager());
581 AddFilter(vc_manager_->video_capture_message_filter());
583 browser_plugin_manager_.reset(new BrowserPluginManager());
584 AddObserver(browser_plugin_manager_.get());
586 #if defined(ENABLE_WEBRTC)
587 peer_connection_tracker_.reset(new PeerConnectionTracker());
588 AddObserver(peer_connection_tracker_.get());
590 p2p_socket_dispatcher_ =
591 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
592 AddFilter(p2p_socket_dispatcher_.get());
594 webrtc_identity_service_.reset(new WebRTCIdentityService());
596 aec_dump_message_filter_ = new AecDumpMessageFilter(
597 GetIOMessageLoopProxy(), message_loop()->task_runner());
598 AddFilter(aec_dump_message_filter_.get());
600 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
601 p2p_socket_dispatcher_.get()));
602 #endif // defined(ENABLE_WEBRTC)
604 audio_input_message_filter_ =
605 new AudioInputMessageFilter(GetIOMessageLoopProxy());
606 AddFilter(audio_input_message_filter_.get());
608 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
609 AddFilter(audio_message_filter_.get());
611 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
612 AddFilter(midi_message_filter_.get());
614 bluetooth_message_filter_ = new BluetoothMessageFilter(thread_safe_sender());
615 AddFilter(bluetooth_message_filter_->GetFilter());
617 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
619 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
621 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
623 GetContentClient()->renderer()->RenderThreadStarted();
625 InitSkiaEventTracer();
626 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
627 skia::SkiaMemoryDumpProvider::GetInstance());
629 const base::CommandLine& command_line =
630 *base::CommandLine::ForCurrentProcess();
632 cc::LayerSettings layer_settings;
633 if (command_line.HasSwitch(switches::kEnableCompositorAnimationTimelines))
634 layer_settings.use_compositor_animation_timelines = true;
635 cc_blink::WebLayerImpl::SetLayerSettings(layer_settings);
637 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
638 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
640 #if defined(OS_MACOSX) && !defined(OS_IOS)
641 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
642 if (is_elastic_overscroll_enabled_) {
643 base::ScopedCFTypeRef<CFStringRef> key(
644 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
645 Boolean key_exists = false;
646 Boolean value = CFPreferencesGetAppBooleanValue(
647 key, kCFPreferencesCurrentApplication, &key_exists);
648 if (key_exists && !value)
649 is_elastic_overscroll_enabled_ = false;
651 #else
652 is_elastic_overscroll_enabled_ = false;
653 #endif
655 std::string image_texture_target_string =
656 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
657 bool parsed_image_texture_target = base::StringToUint(
658 image_texture_target_string, &use_image_texture_target_);
659 DCHECK(parsed_image_texture_target);
661 if (command_line.HasSwitch(switches::kDisableLCDText)) {
662 is_lcd_text_enabled_ = false;
663 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
664 is_lcd_text_enabled_ = true;
665 } else {
666 #if defined(OS_ANDROID)
667 is_lcd_text_enabled_ = false;
668 #else
669 is_lcd_text_enabled_ = true;
670 #endif
673 is_gpu_rasterization_enabled_ =
674 command_line.HasSwitch(switches::kEnableGpuRasterization);
675 is_gpu_rasterization_forced_ =
676 command_line.HasSwitch(switches::kForceGpuRasterization);
678 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
679 std::string string_value = command_line.GetSwitchValueASCII(
680 switches::kGpuRasterizationMSAASampleCount);
681 bool parsed_msaa_sample_count =
682 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
683 DCHECK(parsed_msaa_sample_count) << string_value;
684 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
685 } else {
686 gpu_rasterization_msaa_sample_count_ = 0;
689 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
690 is_distance_field_text_enabled_ = false;
691 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
692 is_distance_field_text_enabled_ = true;
693 } else {
694 is_distance_field_text_enabled_ = false;
697 // Note that under Linux, the media library will normally already have
698 // been initialized by the Zygote before this instance became a Renderer.
699 media::InitializeMediaLibrary();
701 memory_pressure_listener_.reset(new base::MemoryPressureListener(
702 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
704 is_gather_pixel_refs_enabled_ = false;
706 int num_raster_threads = 0;
707 std::string string_value =
708 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
709 bool parsed_num_raster_threads =
710 base::StringToInt(string_value, &num_raster_threads);
711 DCHECK(parsed_num_raster_threads) << string_value;
712 DCHECK_GT(num_raster_threads, 0);
714 // Note: Currently, gathering of pixel refs when using a single
715 // raster thread doesn't provide any benefit. This might change
716 // in the future but we avoid it for now to reduce the cost of
717 // Picture::Create.
718 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
720 base::SimpleThread::Options thread_options;
721 #if defined(OS_ANDROID) || defined(OS_LINUX)
722 if (!command_line.HasSwitch(
723 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
724 thread_options.set_priority(base::ThreadPriority::BACKGROUND);
726 #endif
728 raster_worker_pool_->Start(num_raster_threads, thread_options);
730 // TODO(boliu): In single process, browser main loop should set up the
731 // discardable memory manager, and should skip this if kSingleProcess.
732 // See crbug.com/503724.
733 base::DiscardableMemoryAllocator::SetInstance(
734 ChildThreadImpl::discardable_shared_memory_manager());
736 service_registry()->AddService<RenderFrameSetup>(
737 base::Bind(CreateRenderFrameSetup));
738 service_registry()->AddService<EmbeddedWorkerSetup>(
739 base::Bind(CreateEmbeddedWorkerSetup));
741 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
744 RenderThreadImpl::~RenderThreadImpl() {
747 void RenderThreadImpl::Shutdown() {
748 FOR_EACH_OBSERVER(
749 RenderProcessObserver, observers_, OnRenderProcessShutdown());
751 ChildThreadImpl::Shutdown();
753 if (memory_observer_) {
754 message_loop()->RemoveTaskObserver(memory_observer_.get());
755 memory_observer_.reset();
758 // Wait for all databases to be closed.
759 if (blink_platform_impl_) {
760 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
761 // processing timer events while we're already in the process of shutting
762 // down blink, put a ScopePageLoadDeferrer on the stack.
763 WebView::willEnterModalLoop();
764 blink_platform_impl_->web_database_observer_impl()
765 ->WaitForAllDatabasesToClose();
766 WebView::didExitModalLoop();
769 // Shutdown in reverse of the initialization order.
770 if (devtools_agent_message_filter_.get()) {
771 RemoveFilter(devtools_agent_message_filter_.get());
772 devtools_agent_message_filter_ = NULL;
775 RemoveFilter(audio_input_message_filter_.get());
776 audio_input_message_filter_ = NULL;
778 #if defined(ENABLE_WEBRTC)
779 RTCPeerConnectionHandler::DestructAllHandlers();
780 // |peer_connection_factory_| cannot be deleted until after the main message
781 // loop has been destroyed. This is because there may be pending tasks that
782 // hold on to objects produced by the PC factory that depend on threads owned
783 // by the PC factory. Once those tasks have been freed, the factory can be
784 // deleted.
785 #endif
786 RemoveFilter(vc_manager_->video_capture_message_filter());
787 vc_manager_.reset();
789 RemoveFilter(db_message_filter_.get());
790 db_message_filter_ = NULL;
792 // Shutdown the file thread if it's running.
793 if (file_thread_)
794 file_thread_->Stop();
796 if (compositor_message_filter_.get()) {
797 RemoveFilter(compositor_message_filter_.get());
798 compositor_message_filter_ = NULL;
801 media_thread_.reset();
803 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
804 RemoveFilter(audio_message_filter_.get());
805 audio_message_filter_ = NULL;
807 compositor_thread_.reset();
809 raster_worker_pool_->Shutdown();
811 main_input_callback_.Cancel();
812 input_handler_manager_.reset();
813 if (input_event_filter_.get()) {
814 RemoveFilter(input_event_filter_.get());
815 input_event_filter_ = NULL;
818 // RemoveEmbeddedWorkerRoute may be called while deleting
819 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
820 // RenderThreadImpl.
821 embedded_worker_dispatcher_.reset();
823 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
824 // hold pointers to V8 objects (e.g., via pending requests).
825 main_thread_indexed_db_dispatcher_.reset();
827 main_thread_compositor_task_runner_ = NULL;
829 // Context providers must be released prior to destroying the GPU channel.
830 gpu_va_context_provider_ = nullptr;
831 shared_main_thread_contexts_ = nullptr;
833 if (gpu_channel_.get())
834 gpu_channel_->DestroyChannel();
836 // TODO(port)
837 #if defined(OS_WIN)
838 // Clean up plugin channels before this thread goes away.
839 NPChannelBase::CleanupChannels();
840 #endif
842 // Shut down the message loop and the renderer scheduler before shutting down
843 // Blink. This prevents a scenario where a pending task in the message loop
844 // accesses Blink objects after Blink shuts down.
845 // This must be at the very end of the shutdown sequence. You must not touch
846 // the message loop after this.
847 renderer_scheduler_->Shutdown();
848 main_message_loop_.reset();
849 if (blink_platform_impl_)
850 blink::shutdown();
852 lazy_tls.Pointer()->Set(NULL);
855 bool RenderThreadImpl::Send(IPC::Message* msg) {
856 // Certain synchronous messages cannot always be processed synchronously by
857 // the browser, e.g., putting up UI and waiting for the user. This could cause
858 // a complete hang of Chrome if a windowed plugin is trying to communicate
859 // with the renderer thread since the browser's UI thread could be stuck
860 // (within a Windows API call) trying to synchronously communicate with the
861 // plugin. The remedy is to pump messages on this thread while the browser
862 // is processing this request. This creates an opportunity for re-entrancy
863 // into WebKit, so we need to take care to disable callbacks, timers, and
864 // pending network loads that could trigger such callbacks.
865 bool pumping_events = false;
866 if (msg->is_sync()) {
867 if (msg->is_caller_pumping_messages()) {
868 pumping_events = true;
872 bool notify_webkit_of_modal_loop = true; // default value
873 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
875 #if defined(ENABLE_PLUGINS)
876 int render_view_id = MSG_ROUTING_NONE;
877 #endif
879 if (pumping_events) {
880 renderer_scheduler_->SuspendTimerQueue();
882 if (notify_webkit_of_modal_loop)
883 WebView::willEnterModalLoop();
884 #if defined(ENABLE_PLUGINS)
885 RenderViewImpl* render_view =
886 RenderViewImpl::FromRoutingID(msg->routing_id());
887 if (render_view) {
888 render_view_id = msg->routing_id();
889 PluginChannelHost::Broadcast(
890 new PluginMsg_SignalModalDialogEvent(render_view_id));
892 #endif
895 bool rv = ChildThreadImpl::Send(msg);
897 if (pumping_events) {
898 #if defined(ENABLE_PLUGINS)
899 if (render_view_id != MSG_ROUTING_NONE) {
900 PluginChannelHost::Broadcast(
901 new PluginMsg_ResetModalDialogEvent(render_view_id));
903 #endif
905 if (notify_webkit_of_modal_loop)
906 WebView::didExitModalLoop();
908 renderer_scheduler_->ResumeTimerQueue();
911 return rv;
914 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
915 return channel();
918 std::string RenderThreadImpl::GetLocale() {
919 // The browser process should have passed the locale to the renderer via the
920 // --lang command line flag.
921 const base::CommandLine& parsed_command_line =
922 *base::CommandLine::ForCurrentProcess();
923 const std::string& lang =
924 parsed_command_line.GetSwitchValueASCII(switches::kLang);
925 DCHECK(!lang.empty());
926 return lang;
929 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
930 return sync_message_filter();
933 scoped_refptr<base::SingleThreadTaskRunner>
934 RenderThreadImpl::GetIOMessageLoopProxy() {
935 return ChildProcess::current()->io_task_runner();
938 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
939 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
940 PendingRenderFrameConnectMap::iterator it =
941 pending_render_frame_connects_.find(routing_id);
942 if (it == pending_render_frame_connects_.end())
943 return;
945 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
946 if (!frame)
947 return;
949 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
950 mojo::InterfaceRequest<mojo::ServiceProvider> services(
951 connection->services().Pass());
952 mojo::ServiceProviderPtr exposed_services(
953 connection->exposed_services().Pass());
954 exposed_services.set_connection_error_handler(mojo::Closure());
955 pending_render_frame_connects_.erase(it);
957 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
960 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
961 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
964 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
965 IPC::Listener* listener) {
966 AddRoute(routing_id, listener);
967 if (devtools_agent_message_filter_.get()) {
968 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
969 routing_id);
973 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
974 RemoveRoute(routing_id);
975 if (devtools_agent_message_filter_.get()) {
976 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
977 routing_id);
981 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
982 int routing_id,
983 mojo::InterfaceRequest<mojo::ServiceProvider> services,
984 mojo::ServiceProviderPtr exposed_services) {
985 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
986 pending_render_frame_connects_.insert(std::make_pair(
987 routing_id,
988 make_scoped_refptr(new PendingRenderFrameConnect(
989 routing_id, services.Pass(), exposed_services.Pass()))));
990 CHECK(result.second) << "Inserting a duplicate item.";
993 int RenderThreadImpl::GenerateRoutingID() {
994 int routing_id = MSG_ROUTING_NONE;
995 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
996 return routing_id;
999 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
1000 channel()->AddFilter(filter);
1003 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
1004 channel()->RemoveFilter(filter);
1007 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
1008 observers_.AddObserver(observer);
1011 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
1012 observers_.RemoveObserver(observer);
1015 void RenderThreadImpl::SetResourceDispatcherDelegate(
1016 ResourceDispatcherDelegate* delegate) {
1017 resource_dispatcher()->set_delegate(delegate);
1020 void RenderThreadImpl::SetResourceDispatchTaskQueue(
1021 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
1022 // Add a filter that forces resource messages to be dispatched via a
1023 // particular task runner.
1024 resource_scheduling_filter_ =
1025 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
1026 channel()->AddFilter(resource_scheduling_filter_.get());
1028 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1029 // same queue to ensure tasks are executed in the expected order.
1030 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1031 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1034 void RenderThreadImpl::EnsureWebKitInitialized() {
1035 if (blink_platform_impl_)
1036 return;
1038 const base::CommandLine& command_line =
1039 *base::CommandLine::ForCurrentProcess();
1041 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1042 if (command_line.HasSwitch(switches::kEnableVtune))
1043 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1044 #endif
1046 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1048 blink_platform_impl_.reset(
1049 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1050 blink::initialize(blink_platform_impl_.get());
1052 v8::Isolate* isolate = blink::mainThreadIsolate();
1053 isolate->SetCreateHistogramFunction(CreateHistogram);
1054 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1056 main_thread_compositor_task_runner_ =
1057 renderer_scheduler_->CompositorTaskRunner();
1059 main_input_callback_.Reset(
1060 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1061 base::Unretained(this)));
1063 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1065 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1066 if (enable) {
1067 #if defined(OS_ANDROID)
1068 if (SynchronousCompositorFactory* factory =
1069 SynchronousCompositorFactory::GetInstance())
1070 compositor_task_runner_ = factory->GetCompositorTaskRunner();
1071 #endif
1072 if (!compositor_task_runner_.get()) {
1073 compositor_thread_.reset(new base::Thread("Compositor"));
1074 base::Thread::Options compositor_thread_options;
1075 #if defined(OS_ANDROID)
1076 compositor_thread_options.priority = base::ThreadPriority::DISPLAY;
1077 #endif
1078 compositor_thread_->StartWithOptions(compositor_thread_options);
1079 compositor_task_runner_ = compositor_thread_->task_runner();
1080 compositor_task_runner_->PostTask(
1081 FROM_HERE,
1082 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1083 false));
1086 InputHandlerManagerClient* input_handler_manager_client = NULL;
1087 #if defined(OS_ANDROID)
1088 if (SynchronousCompositorFactory* factory =
1089 SynchronousCompositorFactory::GetInstance()) {
1090 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1092 #endif
1093 if (!input_handler_manager_client) {
1094 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1095 new InputEventFilter(main_input_callback_.callback(),
1096 main_thread_compositor_task_runner_,
1097 compositor_task_runner_));
1098 input_handler_manager_client = compositor_input_event_filter.get();
1099 input_event_filter_ = compositor_input_event_filter;
1101 input_handler_manager_.reset(new InputHandlerManager(
1102 compositor_task_runner_, input_handler_manager_client,
1103 renderer_scheduler_.get()));
1106 if (!input_event_filter_.get()) {
1107 // Always provide an input event filter implementation to ensure consistent
1108 // input event scheduling and prioritization.
1109 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1110 // MainThreadInputEventFilter, crbug.com/436057.
1111 input_event_filter_ = new MainThreadInputEventFilter(
1112 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1114 AddFilter(input_event_filter_.get());
1116 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
1117 if (enable)
1118 compositor_impl_side_task_runner = compositor_task_runner_;
1119 else
1120 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
1122 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1123 compositor_impl_side_task_runner.get());
1124 AddFilter(compositor_message_filter_.get());
1126 RenderThreadImpl::RegisterSchemes();
1128 EnableBlinkPlatformLogChannels(
1129 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1131 RenderMediaClient::Initialize();
1133 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1135 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1136 AddFilter(devtools_agent_message_filter_.get());
1138 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1140 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1141 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1143 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1145 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1146 kImageCacheSingleAllocationByteLimit);
1148 // Hook up blink's codecs so skia can call them
1149 SkGraphics::SetImageGeneratorFromEncodedFactory(
1150 blink::WebImageGenerator::create);
1152 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1153 memory_observer_.reset(new MemoryObserver());
1154 message_loop()->AddTaskObserver(memory_observer_.get());
1157 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1158 std::string allowed_ports =
1159 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1160 net::SetExplicitlyAllowedPorts(allowed_ports);
1164 void RenderThreadImpl::RegisterSchemes() {
1165 // swappedout:
1166 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1167 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1168 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1170 // chrome:
1171 WebString chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme));
1172 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1173 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1174 chrome_scheme);
1175 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme);
1176 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme);
1178 // chrome-devtools:
1179 WebString devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme));
1180 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
1183 void RenderThreadImpl::NotifyTimezoneChange() {
1184 NotifyTimezoneChangeOnThisThread();
1185 RenderThread::Get()->PostTaskToAllWebWorkers(
1186 base::Bind(&NotifyTimezoneChangeOnThisThread));
1189 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1190 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1193 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1194 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1197 scoped_ptr<base::SharedMemory>
1198 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1199 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1202 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1203 return shared_bitmap_manager();
1206 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1207 EnsureWebKitInitialized();
1208 WebScriptController::registerExtension(extension);
1211 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1212 idle_notification_delay_in_ms_ = initial_delay_ms;
1213 idle_timer_.Stop();
1214 idle_timer_.Start(FROM_HERE,
1215 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1216 this, &RenderThreadImpl::IdleHandler);
1219 void RenderThreadImpl::IdleHandler() {
1220 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1221 GetContentClient()->renderer()->
1222 RunIdleHandlerWhenWidgetsHidden();
1223 if (run_in_foreground_tab) {
1224 if (idle_notifications_to_skip_ > 0) {
1225 --idle_notifications_to_skip_;
1226 } else {
1227 ReleaseFreeMemory();
1229 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1230 return;
1233 ReleaseFreeMemory();
1235 // Continue the idle timer if the webkit shared timer is not suspended or
1236 // something is left to do.
1237 bool continue_timer = !webkit_shared_timer_suspended_;
1239 if (blink::mainThreadIsolate() &&
1240 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1241 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1242 continue_timer = true;
1245 // Schedule next invocation. When the tab is originally hidden, an invocation
1246 // is scheduled for kInitialIdleHandlerDelayMs in
1247 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1248 // After that, idle calls can be much less frequent, so run at a maximum of
1249 // once every kLongIdleHandlerDelayMs.
1250 // Dampen the delay using the algorithm (if delay is in seconds):
1251 // delay = delay + 1 / (delay + 2)
1252 // Using floor(delay) has a dampening effect such as:
1253 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1254 // If the delay is in milliseconds, the above formula is equivalent to:
1255 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1256 // which is equivalent to
1257 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1258 if (continue_timer) {
1259 ScheduleIdleHandler(
1260 std::max(kLongIdleHandlerDelayMs,
1261 idle_notification_delay_in_ms_ +
1262 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1264 } else {
1265 idle_timer_.Stop();
1268 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1271 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1272 return idle_notification_delay_in_ms_;
1275 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1276 int64 idle_notification_delay_in_ms) {
1277 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1280 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1281 child_histogram_message_filter()->SendHistograms(sequence_number);
1284 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1285 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1288 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1289 bool result = false;
1290 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1291 return result;
1294 void RenderThreadImpl::PostponeIdleNotification() {
1295 idle_notifications_to_skip_ = 2;
1298 scoped_refptr<media::GpuVideoAcceleratorFactories>
1299 RenderThreadImpl::GetGpuFactories() {
1300 DCHECK(IsMainThread());
1302 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1304 #if defined(OS_ANDROID)
1305 if (SynchronousCompositorFactory::GetInstance()) {
1306 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1307 DLOG(WARNING) << "Accelerated video decoding is not explicitly disabled, "
1308 "but is not supported by in-process rendering";
1310 return NULL;
1312 #endif
1314 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1315 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1316 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1317 GetMediaThreadTaskRunner();
1318 if (!gpu_va_context_provider_.get() ||
1319 gpu_va_context_provider_->DestroyedOnMainThread()) {
1320 if (!gpu_channel_host.get()) {
1321 gpu_channel_host = EstablishGpuChannelSync(
1322 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1324 blink::WebGraphicsContext3D::Attributes attributes;
1325 bool lose_context_when_out_of_memory = false;
1326 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1327 make_scoped_ptr(
1328 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1329 gpu_channel_host.get(), attributes,
1330 lose_context_when_out_of_memory,
1331 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1332 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1333 NULL)),
1334 GPU_VIDEO_ACCELERATOR_CONTEXT);
1336 if (gpu_va_context_provider_.get()) {
1337 bool enable_video_accelerator =
1338 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1339 std::string image_texture_target_string =
1340 cmd_line->GetSwitchValueASCII(switches::kContentImageTextureTarget);
1341 unsigned image_texture_target = 0;
1342 bool parsed_image_texture_target =
1343 base::StringToUint(image_texture_target_string, &image_texture_target);
1344 DCHECK(parsed_image_texture_target);
1345 CHECK(gpu_channel_.get()) << "Have gpu_va_context_provider but no "
1346 "gpu_channel_. See crbug.com/495185.";
1347 CHECK(gpu_channel_host.get()) << "Have gpu_va_context_provider but lost "
1348 "gpu_channel_. See crbug.com/495185.";
1349 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1350 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_,
1351 image_texture_target, enable_video_accelerator);
1353 return gpu_factories;
1356 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1357 RenderThreadImpl::CreateOffscreenContext3d() {
1358 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1359 bool lose_context_when_out_of_memory = true;
1361 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1362 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1363 return make_scoped_ptr(
1364 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1365 gpu_channel_host.get(),
1366 attributes,
1367 lose_context_when_out_of_memory,
1368 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1369 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1370 NULL));
1373 scoped_refptr<cc_blink::ContextProviderWebContext>
1374 RenderThreadImpl::SharedMainThreadContextProvider() {
1375 DCHECK(IsMainThread());
1376 if (!shared_main_thread_contexts_.get() ||
1377 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1378 shared_main_thread_contexts_ = NULL;
1379 #if defined(OS_ANDROID)
1380 SynchronousCompositorFactory* factory =
1381 SynchronousCompositorFactory::GetInstance();
1382 if (factory && factory->OverrideWithFactory()) {
1383 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1384 GetOffscreenAttribs(), "Offscreen-MainThread");
1386 #endif
1387 if (!shared_main_thread_contexts_.get()) {
1388 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1389 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT);
1391 if (shared_main_thread_contexts_.get() &&
1392 !shared_main_thread_contexts_->BindToCurrentThread())
1393 shared_main_thread_contexts_ = NULL;
1395 return shared_main_thread_contexts_;
1398 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1399 if (!audio_renderer_mixer_manager_) {
1400 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1401 GetAudioHardwareConfig()));
1404 return audio_renderer_mixer_manager_.get();
1407 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1408 if (!audio_hardware_config_) {
1409 media::AudioParameters input_params;
1410 media::AudioParameters output_params;
1411 Send(new ViewHostMsg_GetAudioHardwareConfig(
1412 &input_params, &output_params));
1414 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1415 input_params, output_params));
1418 return audio_hardware_config_.get();
1421 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1422 return ChildProcess::current()->GetShutDownEvent();
1425 #if defined(OS_WIN)
1426 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1427 const base::string16& str) {
1428 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1431 #endif // OS_WIN
1433 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1434 return service_registry();
1437 bool RenderThreadImpl::IsGpuRasterizationForced() {
1438 return is_gpu_rasterization_forced_;
1441 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1442 return is_gpu_rasterization_enabled_;
1445 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1446 return gpu_rasterization_msaa_sample_count_;
1449 bool RenderThreadImpl::IsLcdTextEnabled() {
1450 return is_lcd_text_enabled_;
1453 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1454 return is_distance_field_text_enabled_;
1457 bool RenderThreadImpl::IsZeroCopyEnabled() {
1458 return is_zero_copy_enabled_;
1461 bool RenderThreadImpl::IsOneCopyEnabled() {
1462 return is_one_copy_enabled_;
1465 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1466 return is_elastic_overscroll_enabled_;
1469 uint32 RenderThreadImpl::GetImageTextureTarget() {
1470 return use_image_texture_target_;
1473 scoped_refptr<base::SingleThreadTaskRunner>
1474 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1475 return main_thread_compositor_task_runner_;
1478 scoped_refptr<base::SingleThreadTaskRunner>
1479 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1480 return compositor_task_runner_;
1483 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1484 return gpu_memory_buffer_manager();
1487 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1488 return renderer_scheduler_.get();
1491 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1492 return SharedMainThreadContextProvider().get();
1495 scoped_ptr<cc::BeginFrameSource>
1496 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1497 #if defined(OS_ANDROID)
1498 if (SynchronousCompositorFactory* factory =
1499 SynchronousCompositorFactory::GetInstance()) {
1500 return factory->CreateExternalBeginFrameSource(routing_id);
1502 #endif
1503 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1504 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1507 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1508 return raster_worker_pool_->GetTaskGraphRunner();
1511 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1512 return is_gather_pixel_refs_enabled_;
1515 bool RenderThreadImpl::IsMainThread() {
1516 return !!current();
1519 scoped_refptr<base::SingleThreadTaskRunner>
1520 RenderThreadImpl::GetIOThreadTaskRunner() {
1521 return io_thread_task_runner_;
1524 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1525 size_t size) {
1526 return scoped_ptr<base::SharedMemory>(
1527 HostAllocateSharedMemoryBuffer(size));
1530 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1531 int32 surface_id,
1532 const GPUCreateCommandBufferConfig& init_params,
1533 int32 route_id) {
1534 TRACE_EVENT1("gpu",
1535 "RenderThreadImpl::CreateViewCommandBuffer",
1536 "surface_id",
1537 surface_id);
1539 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1540 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1541 surface_id,
1542 init_params,
1543 route_id,
1544 &result);
1546 // Allow calling this from the compositor thread.
1547 thread_safe_sender()->Send(message);
1549 return result;
1552 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1553 notify_webkit_of_modal_loop_ = false;
1556 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1557 base::ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1558 RenderProcessObserver* observer;
1559 while ((observer = it.GetNext()) != NULL) {
1560 if (observer->OnControlMessageReceived(msg))
1561 return true;
1564 // Some messages are handled by delegates.
1565 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1566 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1567 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1568 return true;
1571 bool handled = true;
1572 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1573 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1574 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1575 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1576 OnSetZoomLevelForCurrentURL)
1577 // TODO(port): removed from render_messages_internal.h;
1578 // is there a new non-windows message I should add here?
1579 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1580 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1581 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1582 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1583 #if defined(OS_ANDROID)
1584 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1585 OnSetWebKitSharedTimersSuspended)
1586 #endif
1587 #if defined(OS_MACOSX)
1588 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1589 #endif
1590 #if defined(ENABLE_PLUGINS)
1591 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1592 #endif
1593 IPC_MESSAGE_UNHANDLED(handled = false)
1594 IPC_END_MESSAGE_MAP()
1595 return handled;
1598 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params) {
1599 CompositorDependencies* compositor_deps = this;
1600 RenderFrameImpl::CreateFrame(
1601 params.routing_id, params.parent_routing_id,
1602 params.previous_sibling_routing_id, params.proxy_routing_id,
1603 params.replication_state, compositor_deps, params.widget_params);
1606 void RenderThreadImpl::OnCreateNewFrameProxy(
1607 int routing_id,
1608 int parent_routing_id,
1609 int render_view_routing_id,
1610 const FrameReplicationState& replicated_state) {
1611 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1612 render_view_routing_id, replicated_state);
1615 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1616 const std::string& host,
1617 double zoom_level) {
1618 RenderViewZoomer zoomer(scheme, host, zoom_level);
1619 RenderView::ForEach(&zoomer);
1622 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1623 EnsureWebKitInitialized();
1624 CompositorDependencies* compositor_deps = this;
1625 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1626 RenderViewImpl::Create(compositor_deps, params, false);
1629 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1630 CauseForGpuLaunch cause_for_gpu_launch) {
1631 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1633 if (gpu_channel_.get()) {
1634 // Do nothing if we already have a GPU channel or are already
1635 // establishing one.
1636 if (!gpu_channel_->IsLost())
1637 return gpu_channel_.get();
1639 // Recreate the channel if it has been lost.
1640 gpu_channel_->DestroyChannel();
1641 gpu_channel_ = NULL;
1644 // Ask the browser for the channel name.
1645 int client_id = 0;
1646 IPC::ChannelHandle channel_handle;
1647 gpu::GPUInfo gpu_info;
1648 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1649 &client_id,
1650 &channel_handle,
1651 &gpu_info)) ||
1652 #if defined(OS_POSIX)
1653 channel_handle.socket.fd == -1 ||
1654 #endif
1655 channel_handle.name.empty()) {
1656 // Otherwise cancel the connection.
1657 return NULL;
1660 GetContentClient()->SetGpuInfo(gpu_info);
1662 // Cache some variables that are needed on the compositor thread for our
1663 // implementation of GpuChannelHostFactory.
1664 io_thread_task_runner_ = ChildProcess::current()->io_task_runner();
1666 gpu_channel_ =
1667 GpuChannelHost::Create(this,
1668 gpu_info,
1669 channel_handle,
1670 ChildProcess::current()->GetShutDownEvent(),
1671 gpu_memory_buffer_manager());
1672 return gpu_channel_.get();
1675 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1676 blink::WebMediaStreamCenterClient* client) {
1677 #if defined(OS_ANDROID)
1678 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1679 switches::kDisableWebRTC))
1680 return NULL;
1681 #endif
1683 #if defined(ENABLE_WEBRTC)
1684 if (!media_stream_center_) {
1685 media_stream_center_ = GetContentClient()->renderer()
1686 ->OverrideCreateWebMediaStreamCenter(client);
1687 if (!media_stream_center_) {
1688 scoped_ptr<MediaStreamCenter> media_stream_center(
1689 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1690 media_stream_center_ = media_stream_center.release();
1693 #endif
1694 return media_stream_center_;
1697 #if defined(ENABLE_WEBRTC)
1698 PeerConnectionDependencyFactory*
1699 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1700 return peer_connection_factory_.get();
1702 #endif
1704 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1705 if (!gpu_channel_.get())
1706 return NULL;
1708 if (gpu_channel_->IsLost())
1709 return NULL;
1711 return gpu_channel_.get();
1714 #if defined(ENABLE_PLUGINS)
1715 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1716 EnsureWebKitInitialized();
1717 // The call below will cause a GetPlugins call with refresh=true, but at this
1718 // point we already know that the browser has refreshed its list, so disable
1719 // refresh temporarily to prevent each renderer process causing the list to be
1720 // regenerated.
1721 blink_platform_impl_->set_plugin_refresh_allowed(false);
1722 blink::resetPluginCache(reload_pages);
1723 blink_platform_impl_->set_plugin_refresh_allowed(true);
1725 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1727 #endif
1729 void RenderThreadImpl::OnNetworkTypeChanged(
1730 net::NetworkChangeNotifier::ConnectionType type) {
1731 EnsureWebKitInitialized();
1732 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1733 WebNetworkStateNotifier::setOnLine(online);
1734 FOR_EACH_OBSERVER(
1735 RenderProcessObserver, observers_, NetworkStateChanged(online));
1736 WebNetworkStateNotifier::setWebConnectionType(
1737 NetConnectionTypeToWebConnectionType(type));
1740 void RenderThreadImpl::OnUpdateTimezone(const std::string& zone_id) {
1741 if (!blink_platform_impl_)
1742 return;
1743 if (!zone_id.empty()) {
1744 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
1745 icu::UnicodeString::fromUTF8(zone_id));
1746 icu::TimeZone::adoptDefault(new_zone);
1747 VLOG(1) << "ICU default timezone is set to " << zone_id;
1749 NotifyTimezoneChange();
1752 #if defined(OS_ANDROID)
1753 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1754 EnsureWebKitInitialized();
1755 if (suspend) {
1756 renderer_scheduler_->SuspendTimerQueue();
1757 } else {
1758 renderer_scheduler_->ResumeTimerQueue();
1760 webkit_shared_timer_suspended_ = suspend;
1762 #endif
1764 #if defined(OS_MACOSX)
1765 void RenderThreadImpl::OnUpdateScrollbarTheme(
1766 const ViewMsg_UpdateScrollbarTheme_Params& params) {
1767 EnsureWebKitInitialized();
1768 static_cast<WebScrollbarBehaviorImpl*>(
1769 blink_platform_impl_->scrollbarBehavior())
1770 ->set_jump_on_track_click(params.jump_on_track_click);
1772 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
1773 params.initial_button_delay, params.autoscroll_button_delay,
1774 params.preferred_scroller_style, params.redraw,
1775 params.scroll_animation_enabled, params.button_placement);
1777 #endif
1779 void RenderThreadImpl::OnCreateNewSharedWorker(
1780 const WorkerProcessMsg_CreateWorker_Params& params) {
1781 // EmbeddedSharedWorkerStub will self-destruct.
1782 new EmbeddedSharedWorkerStub(params.url,
1783 params.name,
1784 params.content_security_policy,
1785 params.security_policy_type,
1786 params.pause_on_start,
1787 params.route_id);
1790 void RenderThreadImpl::OnMemoryPressure(
1791 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1792 ReleaseFreeMemory();
1794 // Do not call into blink if it is not initialized.
1795 if (blink_platform_impl_) {
1796 blink::WebCache::pruneAll();
1798 if (blink::mainThreadIsolate()) {
1799 // Trigger full v8 garbage collection on memory pressure notifications.
1800 // This will potentially hang the renderer for a long time, however, when
1801 // we receive a memory pressure notification, we might be about to be
1802 // killed.
1803 blink::mainThreadIsolate()->LowMemoryNotification();
1804 RenderThread::Get()->PostTaskToAllWebWorkers(
1805 base::Bind(&LowMemoryNotificationOnThisThread));
1808 if (memory_pressure_level ==
1809 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1810 // Clear the image cache.
1811 blink::WebImageCache::clear();
1813 // Purge Skia font cache, by setting it to 0 and then again to the
1814 // previous limit.
1815 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1816 SkGraphics::SetFontCacheLimit(font_cache_limit);
1821 scoped_refptr<base::SingleThreadTaskRunner>
1822 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1823 DCHECK(message_loop() == base::MessageLoop::current());
1824 if (!file_thread_) {
1825 file_thread_.reset(new base::Thread("Renderer::FILE"));
1826 file_thread_->Start();
1828 return file_thread_->task_runner();
1831 scoped_refptr<base::SingleThreadTaskRunner>
1832 RenderThreadImpl::GetMediaThreadTaskRunner() {
1833 DCHECK(message_loop() == base::MessageLoop::current());
1834 if (!media_thread_) {
1835 media_thread_.reset(new base::Thread("Media"));
1836 media_thread_->Start();
1838 #if defined(OS_ANDROID)
1839 renderer_demuxer_ = new RendererDemuxerAndroid();
1840 AddFilter(renderer_demuxer_.get());
1841 #endif
1843 return media_thread_->task_runner();
1846 base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
1847 return raster_worker_pool_.get();
1850 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1851 blink_platform_impl_->sampleGamepads(*data);
1854 bool RenderThreadImpl::RendererIsHidden() const {
1855 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1858 void RenderThreadImpl::WidgetCreated() {
1859 bool renderer_was_hidden = RendererIsHidden();
1860 widget_count_++;
1861 if (renderer_was_hidden)
1862 OnRendererVisible();
1865 void RenderThreadImpl::WidgetDestroyed() {
1866 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1867 // unhidden before WidgetDestroyed is called.
1868 DCHECK_GT(widget_count_, 0);
1869 DCHECK_GT(widget_count_, hidden_widget_count_);
1870 widget_count_--;
1871 if (RendererIsHidden())
1872 OnRendererHidden();
1875 void RenderThreadImpl::WidgetHidden() {
1876 DCHECK_LT(hidden_widget_count_, widget_count_);
1877 hidden_widget_count_++;
1878 if (RendererIsHidden())
1879 OnRendererHidden();
1882 void RenderThreadImpl::WidgetRestored() {
1883 bool renderer_was_hidden = RendererIsHidden();
1884 DCHECK_GT(hidden_widget_count_, 0);
1885 hidden_widget_count_--;
1886 if (renderer_was_hidden)
1887 OnRendererVisible();
1890 void RenderThreadImpl::OnRendererHidden() {
1891 renderer_scheduler_->OnRendererHidden();
1893 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1894 // scheduled by the RendererScheduler - http://crbug.com/469210.
1895 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1896 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1899 void RenderThreadImpl::OnRendererVisible() {
1900 renderer_scheduler_->OnRendererVisible();
1902 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1903 return;
1905 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1908 void RenderThreadImpl::ReleaseFreeMemory() {
1909 base::allocator::ReleaseFreeMemory();
1910 discardable_shared_memory_manager()->ReleaseFreeMemory();
1912 if (blink_platform_impl_)
1913 blink::decommitFreeableMemory();
1916 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1917 int routing_id,
1918 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1919 mojo::ServiceProviderPtr exposed_services)
1920 : routing_id_(routing_id),
1921 services_(services.Pass()),
1922 exposed_services_(exposed_services.Pass()) {
1923 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1924 // is received. In that case, the RenderFrameHost should close the connection,
1925 // which is detected by setting an error handler on |exposed_services_|.
1926 exposed_services_.set_connection_error_handler(base::Bind(
1927 &RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError,
1928 base::Unretained(this)));
1931 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1934 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1935 size_t erased =
1936 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1937 routing_id_);
1938 DCHECK_EQ(1u, erased);
1941 } // namespace content