Remove unused did_first_* fields from InternalDocumentStateData.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blobe10b26b9fd9327fb005e850d8028027495fcd73a
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);
656 is_persistent_gpu_memory_buffer_enabled_ =
657 command_line.HasSwitch(switches::kEnablePersistentGpuMemoryBuffer);
659 #if defined(OS_MACOSX) && !defined(OS_IOS)
660 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
661 if (is_elastic_overscroll_enabled_) {
662 base::ScopedCFTypeRef<CFStringRef> key(
663 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
664 Boolean key_exists = false;
665 Boolean value = CFPreferencesGetAppBooleanValue(
666 key, kCFPreferencesCurrentApplication, &key_exists);
667 if (key_exists && !value)
668 is_elastic_overscroll_enabled_ = false;
670 #else
671 is_elastic_overscroll_enabled_ = false;
672 #endif
674 std::string image_texture_target_string =
675 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
676 StringToUintVector(image_texture_target_string, &use_image_texture_targets_);
678 if (command_line.HasSwitch(switches::kDisableLCDText)) {
679 is_lcd_text_enabled_ = false;
680 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
681 is_lcd_text_enabled_ = true;
682 } else {
683 #if defined(OS_ANDROID)
684 is_lcd_text_enabled_ = false;
685 #else
686 is_lcd_text_enabled_ = true;
687 #endif
690 is_gpu_rasterization_enabled_ =
691 command_line.HasSwitch(switches::kEnableGpuRasterization);
692 is_gpu_rasterization_forced_ =
693 command_line.HasSwitch(switches::kForceGpuRasterization);
695 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
696 std::string string_value = command_line.GetSwitchValueASCII(
697 switches::kGpuRasterizationMSAASampleCount);
698 bool parsed_msaa_sample_count =
699 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
700 DCHECK(parsed_msaa_sample_count) << string_value;
701 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
702 } else {
703 gpu_rasterization_msaa_sample_count_ = -1;
706 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
707 is_distance_field_text_enabled_ = false;
708 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
709 is_distance_field_text_enabled_ = true;
710 } else {
711 is_distance_field_text_enabled_ = false;
714 // Note that under Linux, the media library will normally already have
715 // been initialized by the Zygote before this instance became a Renderer.
716 media::InitializeMediaLibrary();
718 memory_pressure_listener_.reset(new base::MemoryPressureListener(
719 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
721 is_gather_pixel_refs_enabled_ = false;
723 int num_raster_threads = 0;
724 std::string string_value =
725 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
726 bool parsed_num_raster_threads =
727 base::StringToInt(string_value, &num_raster_threads);
728 DCHECK(parsed_num_raster_threads) << string_value;
729 DCHECK_GT(num_raster_threads, 0);
731 // Note: Currently, gathering of pixel refs when using a single
732 // raster thread doesn't provide any benefit. This might change
733 // in the future but we avoid it for now to reduce the cost of
734 // Picture::Create.
735 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
737 base::SimpleThread::Options thread_options;
738 #if defined(OS_ANDROID) || defined(OS_LINUX)
739 if (!command_line.HasSwitch(
740 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
741 thread_options.set_priority(base::ThreadPriority::BACKGROUND);
743 #endif
745 raster_worker_pool_->Start(num_raster_threads, thread_options);
747 // TODO(boliu): In single process, browser main loop should set up the
748 // discardable memory manager, and should skip this if kSingleProcess.
749 // See crbug.com/503724.
750 base::DiscardableMemoryAllocator::SetInstance(
751 ChildThreadImpl::discardable_shared_memory_manager());
753 service_registry()->AddService<RenderFrameSetup>(
754 base::Bind(CreateRenderFrameSetup));
755 service_registry()->AddService<EmbeddedWorkerSetup>(
756 base::Bind(CreateEmbeddedWorkerSetup));
758 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
761 RenderThreadImpl::~RenderThreadImpl() {
764 void RenderThreadImpl::Shutdown() {
765 FOR_EACH_OBSERVER(
766 RenderProcessObserver, observers_, OnRenderProcessShutdown());
768 ChildThreadImpl::Shutdown();
770 if (memory_observer_) {
771 message_loop()->RemoveTaskObserver(memory_observer_.get());
772 memory_observer_.reset();
775 // Wait for all databases to be closed.
776 if (blink_platform_impl_) {
777 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
778 // processing timer events while we're already in the process of shutting
779 // down blink, put a ScopePageLoadDeferrer on the stack.
780 WebView::willEnterModalLoop();
781 blink_platform_impl_->web_database_observer_impl()
782 ->WaitForAllDatabasesToClose();
783 WebView::didExitModalLoop();
786 // Shutdown in reverse of the initialization order.
787 if (devtools_agent_message_filter_.get()) {
788 RemoveFilter(devtools_agent_message_filter_.get());
789 devtools_agent_message_filter_ = NULL;
792 RemoveFilter(audio_input_message_filter_.get());
793 audio_input_message_filter_ = NULL;
795 #if defined(ENABLE_WEBRTC)
796 RTCPeerConnectionHandler::DestructAllHandlers();
797 // |peer_connection_factory_| cannot be deleted until after the main message
798 // loop has been destroyed. This is because there may be pending tasks that
799 // hold on to objects produced by the PC factory that depend on threads owned
800 // by the PC factory. Once those tasks have been freed, the factory can be
801 // deleted.
802 #endif
803 RemoveFilter(vc_manager_->video_capture_message_filter());
804 vc_manager_.reset();
806 RemoveFilter(db_message_filter_.get());
807 db_message_filter_ = NULL;
809 // Shutdown the file thread if it's running.
810 if (file_thread_)
811 file_thread_->Stop();
813 if (compositor_message_filter_.get()) {
814 RemoveFilter(compositor_message_filter_.get());
815 compositor_message_filter_ = NULL;
818 media_thread_.reset();
820 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
821 RemoveFilter(audio_message_filter_.get());
822 audio_message_filter_ = NULL;
824 compositor_thread_.reset();
826 raster_worker_pool_->Shutdown();
828 main_input_callback_.Cancel();
829 input_handler_manager_.reset();
830 if (input_event_filter_.get()) {
831 RemoveFilter(input_event_filter_.get());
832 input_event_filter_ = NULL;
835 // RemoveEmbeddedWorkerRoute may be called while deleting
836 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
837 // RenderThreadImpl.
838 embedded_worker_dispatcher_.reset();
840 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
841 // hold pointers to V8 objects (e.g., via pending requests).
842 main_thread_indexed_db_dispatcher_.reset();
844 main_thread_compositor_task_runner_ = NULL;
846 // Context providers must be released prior to destroying the GPU channel.
847 gpu_va_context_provider_ = nullptr;
848 shared_main_thread_contexts_ = nullptr;
850 if (gpu_channel_.get())
851 gpu_channel_->DestroyChannel();
853 // TODO(port)
854 #if defined(OS_WIN)
855 // Clean up plugin channels before this thread goes away.
856 NPChannelBase::CleanupChannels();
857 #endif
859 // Shut down the message loop and the renderer scheduler before shutting down
860 // Blink. This prevents a scenario where a pending task in the message loop
861 // accesses Blink objects after Blink shuts down.
862 // This must be at the very end of the shutdown sequence. You must not touch
863 // the message loop after this.
864 renderer_scheduler_->Shutdown();
865 main_message_loop_.reset();
866 if (blink_platform_impl_)
867 blink::shutdown();
869 lazy_tls.Pointer()->Set(NULL);
872 bool RenderThreadImpl::Send(IPC::Message* msg) {
873 // Certain synchronous messages cannot always be processed synchronously by
874 // the browser, e.g., putting up UI and waiting for the user. This could cause
875 // a complete hang of Chrome if a windowed plugin is trying to communicate
876 // with the renderer thread since the browser's UI thread could be stuck
877 // (within a Windows API call) trying to synchronously communicate with the
878 // plugin. The remedy is to pump messages on this thread while the browser
879 // is processing this request. This creates an opportunity for re-entrancy
880 // into WebKit, so we need to take care to disable callbacks, timers, and
881 // pending network loads that could trigger such callbacks.
882 bool pumping_events = false;
883 if (msg->is_sync()) {
884 if (msg->is_caller_pumping_messages()) {
885 pumping_events = true;
889 bool notify_webkit_of_modal_loop = true; // default value
890 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
892 #if defined(ENABLE_PLUGINS)
893 int render_view_id = MSG_ROUTING_NONE;
894 #endif
896 if (pumping_events) {
897 renderer_scheduler_->SuspendTimerQueue();
899 if (notify_webkit_of_modal_loop)
900 WebView::willEnterModalLoop();
901 #if defined(ENABLE_PLUGINS)
902 RenderViewImpl* render_view =
903 RenderViewImpl::FromRoutingID(msg->routing_id());
904 if (render_view) {
905 render_view_id = msg->routing_id();
906 PluginChannelHost::Broadcast(
907 new PluginMsg_SignalModalDialogEvent(render_view_id));
909 #endif
912 bool rv = ChildThreadImpl::Send(msg);
914 if (pumping_events) {
915 #if defined(ENABLE_PLUGINS)
916 if (render_view_id != MSG_ROUTING_NONE) {
917 PluginChannelHost::Broadcast(
918 new PluginMsg_ResetModalDialogEvent(render_view_id));
920 #endif
922 if (notify_webkit_of_modal_loop)
923 WebView::didExitModalLoop();
925 renderer_scheduler_->ResumeTimerQueue();
928 return rv;
931 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
932 return channel();
935 std::string RenderThreadImpl::GetLocale() {
936 // The browser process should have passed the locale to the renderer via the
937 // --lang command line flag.
938 const base::CommandLine& parsed_command_line =
939 *base::CommandLine::ForCurrentProcess();
940 const std::string& lang =
941 parsed_command_line.GetSwitchValueASCII(switches::kLang);
942 DCHECK(!lang.empty());
943 return lang;
946 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
947 return sync_message_filter();
950 scoped_refptr<base::SingleThreadTaskRunner>
951 RenderThreadImpl::GetIOMessageLoopProxy() {
952 return ChildProcess::current()->io_task_runner();
955 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
956 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
957 PendingRenderFrameConnectMap::iterator it =
958 pending_render_frame_connects_.find(routing_id);
959 if (it == pending_render_frame_connects_.end())
960 return;
962 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
963 if (!frame)
964 return;
966 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
967 mojo::InterfaceRequest<mojo::ServiceProvider> services(
968 connection->services().Pass());
969 mojo::ServiceProviderPtr exposed_services(
970 connection->exposed_services().Pass());
971 exposed_services.set_connection_error_handler(mojo::Closure());
972 pending_render_frame_connects_.erase(it);
974 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
977 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
978 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
981 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
982 IPC::Listener* listener) {
983 AddRoute(routing_id, listener);
984 if (devtools_agent_message_filter_.get()) {
985 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
986 routing_id);
990 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
991 RemoveRoute(routing_id);
992 if (devtools_agent_message_filter_.get()) {
993 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
994 routing_id);
998 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
999 int routing_id,
1000 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1001 mojo::ServiceProviderPtr exposed_services) {
1002 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
1003 pending_render_frame_connects_.insert(std::make_pair(
1004 routing_id,
1005 make_scoped_refptr(new PendingRenderFrameConnect(
1006 routing_id, services.Pass(), exposed_services.Pass()))));
1007 CHECK(result.second) << "Inserting a duplicate item.";
1010 int RenderThreadImpl::GenerateRoutingID() {
1011 int routing_id = MSG_ROUTING_NONE;
1012 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
1013 return routing_id;
1016 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
1017 channel()->AddFilter(filter);
1020 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
1021 channel()->RemoveFilter(filter);
1024 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
1025 observers_.AddObserver(observer);
1028 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
1029 observers_.RemoveObserver(observer);
1032 void RenderThreadImpl::SetResourceDispatcherDelegate(
1033 ResourceDispatcherDelegate* delegate) {
1034 resource_dispatcher()->set_delegate(delegate);
1037 void RenderThreadImpl::SetResourceDispatchTaskQueue(
1038 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
1039 // Add a filter that forces resource messages to be dispatched via a
1040 // particular task runner.
1041 resource_scheduling_filter_ =
1042 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
1043 channel()->AddFilter(resource_scheduling_filter_.get());
1045 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1046 // same queue to ensure tasks are executed in the expected order.
1047 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1048 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1051 void RenderThreadImpl::EnsureWebKitInitialized() {
1052 if (blink_platform_impl_)
1053 return;
1055 const base::CommandLine& command_line =
1056 *base::CommandLine::ForCurrentProcess();
1058 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1059 if (command_line.HasSwitch(switches::kEnableVtune))
1060 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1061 #endif
1063 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1065 blink_platform_impl_.reset(
1066 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1067 blink::initialize(blink_platform_impl_.get());
1069 v8::Isolate* isolate = blink::mainThreadIsolate();
1070 isolate->SetCreateHistogramFunction(CreateHistogram);
1071 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1073 main_thread_compositor_task_runner_ =
1074 renderer_scheduler_->CompositorTaskRunner();
1076 main_input_callback_.Reset(
1077 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1078 base::Unretained(this)));
1080 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1082 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1083 if (enable) {
1084 #if defined(OS_ANDROID)
1085 if (SynchronousCompositorFactory* factory =
1086 SynchronousCompositorFactory::GetInstance())
1087 compositor_task_runner_ = factory->GetCompositorTaskRunner();
1088 #endif
1089 if (!compositor_task_runner_.get()) {
1090 compositor_thread_.reset(new base::Thread("Compositor"));
1091 base::Thread::Options compositor_thread_options;
1092 #if defined(OS_ANDROID)
1093 compositor_thread_options.priority = base::ThreadPriority::DISPLAY;
1094 #endif
1095 compositor_thread_->StartWithOptions(compositor_thread_options);
1096 compositor_task_runner_ = compositor_thread_->task_runner();
1097 compositor_task_runner_->PostTask(
1098 FROM_HERE,
1099 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1100 false));
1103 InputHandlerManagerClient* input_handler_manager_client = NULL;
1104 #if defined(OS_ANDROID)
1105 if (SynchronousCompositorFactory* factory =
1106 SynchronousCompositorFactory::GetInstance()) {
1107 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1109 #endif
1110 if (!input_handler_manager_client) {
1111 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1112 new InputEventFilter(main_input_callback_.callback(),
1113 main_thread_compositor_task_runner_,
1114 compositor_task_runner_));
1115 input_handler_manager_client = compositor_input_event_filter.get();
1116 input_event_filter_ = compositor_input_event_filter;
1118 input_handler_manager_.reset(new InputHandlerManager(
1119 compositor_task_runner_, input_handler_manager_client,
1120 renderer_scheduler_.get()));
1123 if (!input_event_filter_.get()) {
1124 // Always provide an input event filter implementation to ensure consistent
1125 // input event scheduling and prioritization.
1126 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1127 // MainThreadInputEventFilter, crbug.com/436057.
1128 input_event_filter_ = new MainThreadInputEventFilter(
1129 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1131 AddFilter(input_event_filter_.get());
1133 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
1134 if (enable)
1135 compositor_impl_side_task_runner = compositor_task_runner_;
1136 else
1137 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
1139 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1140 compositor_impl_side_task_runner.get());
1141 AddFilter(compositor_message_filter_.get());
1143 RenderThreadImpl::RegisterSchemes();
1145 EnableBlinkPlatformLogChannels(
1146 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1148 RenderMediaClient::Initialize();
1150 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1152 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1153 AddFilter(devtools_agent_message_filter_.get());
1155 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1157 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1158 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1160 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1162 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1163 kImageCacheSingleAllocationByteLimit);
1165 // Hook up blink's codecs so skia can call them
1166 SkGraphics::SetImageGeneratorFromEncodedFactory(
1167 blink::WebImageGenerator::create);
1169 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1170 memory_observer_.reset(new MemoryObserver());
1171 message_loop()->AddTaskObserver(memory_observer_.get());
1174 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1175 std::string allowed_ports =
1176 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1177 net::SetExplicitlyAllowedPorts(allowed_ports);
1181 void RenderThreadImpl::RegisterSchemes() {
1182 // swappedout:
1183 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1184 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1185 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1187 // chrome:
1188 WebString chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme));
1189 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1190 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1191 chrome_scheme);
1192 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme);
1193 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme);
1195 // chrome-devtools:
1196 WebString devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme));
1197 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
1200 void RenderThreadImpl::NotifyTimezoneChange() {
1201 NotifyTimezoneChangeOnThisThread();
1202 RenderThread::Get()->PostTaskToAllWebWorkers(
1203 base::Bind(&NotifyTimezoneChangeOnThisThread));
1206 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1207 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1210 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1211 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1214 scoped_ptr<base::SharedMemory>
1215 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1216 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1219 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1220 return shared_bitmap_manager();
1223 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1224 EnsureWebKitInitialized();
1225 WebScriptController::registerExtension(extension);
1228 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1229 idle_notification_delay_in_ms_ = initial_delay_ms;
1230 idle_timer_.Stop();
1231 idle_timer_.Start(FROM_HERE,
1232 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1233 this, &RenderThreadImpl::IdleHandler);
1236 void RenderThreadImpl::IdleHandler() {
1237 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1238 GetContentClient()->renderer()->
1239 RunIdleHandlerWhenWidgetsHidden();
1240 if (run_in_foreground_tab) {
1241 if (idle_notifications_to_skip_ > 0) {
1242 --idle_notifications_to_skip_;
1243 } else {
1244 ReleaseFreeMemory();
1246 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1247 return;
1250 ReleaseFreeMemory();
1252 // Continue the idle timer if the webkit shared timer is not suspended or
1253 // something is left to do.
1254 bool continue_timer = !webkit_shared_timer_suspended_;
1256 if (blink::mainThreadIsolate() &&
1257 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1258 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1259 continue_timer = true;
1262 // Schedule next invocation. When the tab is originally hidden, an invocation
1263 // is scheduled for kInitialIdleHandlerDelayMs in
1264 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1265 // After that, idle calls can be much less frequent, so run at a maximum of
1266 // once every kLongIdleHandlerDelayMs.
1267 // Dampen the delay using the algorithm (if delay is in seconds):
1268 // delay = delay + 1 / (delay + 2)
1269 // Using floor(delay) has a dampening effect such as:
1270 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1271 // If the delay is in milliseconds, the above formula is equivalent to:
1272 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1273 // which is equivalent to
1274 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1275 if (continue_timer) {
1276 ScheduleIdleHandler(
1277 std::max(kLongIdleHandlerDelayMs,
1278 idle_notification_delay_in_ms_ +
1279 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1281 } else {
1282 idle_timer_.Stop();
1285 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1288 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1289 return idle_notification_delay_in_ms_;
1292 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1293 int64 idle_notification_delay_in_ms) {
1294 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1297 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1298 child_histogram_message_filter()->SendHistograms(sequence_number);
1301 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1302 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1305 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1306 bool result = false;
1307 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1308 return result;
1311 void RenderThreadImpl::PostponeIdleNotification() {
1312 idle_notifications_to_skip_ = 2;
1315 scoped_refptr<media::GpuVideoAcceleratorFactories>
1316 RenderThreadImpl::GetGpuFactories() {
1317 DCHECK(IsMainThread());
1319 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1321 #if defined(OS_ANDROID)
1322 if (SynchronousCompositorFactory::GetInstance()) {
1323 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1324 DLOG(WARNING) << "Accelerated video decoding is not explicitly disabled, "
1325 "but is not supported by in-process rendering";
1327 return NULL;
1329 #endif
1331 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1332 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1333 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1334 GetMediaThreadTaskRunner();
1335 if (!gpu_va_context_provider_.get() ||
1336 gpu_va_context_provider_->DestroyedOnMainThread()) {
1337 if (!gpu_channel_host.get()) {
1338 gpu_channel_host = EstablishGpuChannelSync(
1339 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1341 blink::WebGraphicsContext3D::Attributes attributes;
1342 bool lose_context_when_out_of_memory = false;
1343 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1344 make_scoped_ptr(
1345 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1346 gpu_channel_host.get(), attributes,
1347 lose_context_when_out_of_memory,
1348 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1349 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1350 NULL)),
1351 GPU_VIDEO_ACCELERATOR_CONTEXT);
1353 if (gpu_va_context_provider_.get()) {
1354 const bool enable_video_accelerator =
1355 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1356 const bool enable_gpu_memory_buffer_video_frames =
1357 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
1358 std::string image_texture_target_string =
1359 cmd_line->GetSwitchValueASCII(switches::kVideoImageTextureTarget);
1360 unsigned image_texture_target = 0;
1361 const bool parsed_image_texture_target =
1362 base::StringToUint(image_texture_target_string, &image_texture_target);
1363 DCHECK(parsed_image_texture_target);
1364 CHECK(gpu_channel_.get()) << "Have gpu_va_context_provider but no "
1365 "gpu_channel_. See crbug.com/495185.";
1366 CHECK(gpu_channel_host.get()) << "Have gpu_va_context_provider but lost "
1367 "gpu_channel_. See crbug.com/495185.";
1368 media::VideoPixelFormat video_pixel_format = media::PIXEL_FORMAT_I420;
1369 #if defined(OS_MACOSX)
1370 // TODO(dcastagna): Check that the extension is available.
1371 video_pixel_format = media::PIXEL_FORMAT_UYVY;
1372 #endif
1373 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1374 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_,
1375 enable_gpu_memory_buffer_video_frames, image_texture_target,
1376 video_pixel_format, enable_video_accelerator);
1378 return gpu_factories;
1381 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1382 RenderThreadImpl::CreateOffscreenContext3d() {
1383 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1384 bool lose_context_when_out_of_memory = true;
1386 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1387 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1388 return make_scoped_ptr(
1389 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1390 gpu_channel_host.get(),
1391 attributes,
1392 lose_context_when_out_of_memory,
1393 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1394 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1395 NULL));
1398 scoped_refptr<cc_blink::ContextProviderWebContext>
1399 RenderThreadImpl::SharedMainThreadContextProvider() {
1400 DCHECK(IsMainThread());
1401 if (!shared_main_thread_contexts_.get() ||
1402 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1403 shared_main_thread_contexts_ = NULL;
1404 #if defined(OS_ANDROID)
1405 SynchronousCompositorFactory* factory =
1406 SynchronousCompositorFactory::GetInstance();
1407 if (factory && factory->OverrideWithFactory()) {
1408 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1409 GetOffscreenAttribs(), "Offscreen-MainThread");
1411 #endif
1412 if (!shared_main_thread_contexts_.get()) {
1413 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1414 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT);
1416 if (shared_main_thread_contexts_.get() &&
1417 !shared_main_thread_contexts_->BindToCurrentThread())
1418 shared_main_thread_contexts_ = NULL;
1420 return shared_main_thread_contexts_;
1423 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1424 if (!audio_renderer_mixer_manager_) {
1425 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1426 GetAudioHardwareConfig()));
1429 return audio_renderer_mixer_manager_.get();
1432 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1433 if (!audio_hardware_config_) {
1434 media::AudioParameters input_params;
1435 media::AudioParameters output_params;
1436 Send(new ViewHostMsg_GetAudioHardwareConfig(
1437 &input_params, &output_params));
1439 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1440 input_params, output_params));
1443 return audio_hardware_config_.get();
1446 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1447 return ChildProcess::current()->GetShutDownEvent();
1450 #if defined(OS_WIN)
1451 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1452 const base::string16& str) {
1453 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1456 #endif // OS_WIN
1458 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1459 return service_registry();
1462 bool RenderThreadImpl::IsGpuRasterizationForced() {
1463 return is_gpu_rasterization_forced_;
1466 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1467 return is_gpu_rasterization_enabled_;
1470 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1471 return gpu_rasterization_msaa_sample_count_;
1474 bool RenderThreadImpl::IsLcdTextEnabled() {
1475 return is_lcd_text_enabled_;
1478 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1479 return is_distance_field_text_enabled_;
1482 bool RenderThreadImpl::IsZeroCopyEnabled() {
1483 return is_zero_copy_enabled_;
1486 bool RenderThreadImpl::IsOneCopyEnabled() {
1487 return is_one_copy_enabled_;
1490 bool RenderThreadImpl::IsPersistentGpuMemoryBufferEnabled() {
1491 return is_persistent_gpu_memory_buffer_enabled_;
1494 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1495 return is_elastic_overscroll_enabled_;
1498 std::vector<unsigned> RenderThreadImpl::GetImageTextureTargets() {
1499 return use_image_texture_targets_;
1502 scoped_refptr<base::SingleThreadTaskRunner>
1503 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1504 return main_thread_compositor_task_runner_;
1507 scoped_refptr<base::SingleThreadTaskRunner>
1508 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1509 return compositor_task_runner_;
1512 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1513 return gpu_memory_buffer_manager();
1516 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1517 return renderer_scheduler_.get();
1520 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1521 return SharedMainThreadContextProvider().get();
1524 scoped_ptr<cc::BeginFrameSource>
1525 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1526 #if defined(OS_ANDROID)
1527 if (SynchronousCompositorFactory* factory =
1528 SynchronousCompositorFactory::GetInstance()) {
1529 return factory->CreateExternalBeginFrameSource(routing_id);
1531 #endif
1532 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1533 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1536 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1537 return raster_worker_pool_->GetTaskGraphRunner();
1540 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1541 return is_gather_pixel_refs_enabled_;
1544 bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1545 return is_threaded_animation_enabled_;
1548 bool RenderThreadImpl::IsMainThread() {
1549 return !!current();
1552 scoped_refptr<base::SingleThreadTaskRunner>
1553 RenderThreadImpl::GetIOThreadTaskRunner() {
1554 return io_thread_task_runner_;
1557 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1558 size_t size) {
1559 return scoped_ptr<base::SharedMemory>(
1560 HostAllocateSharedMemoryBuffer(size));
1563 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1564 int32 surface_id,
1565 const GPUCreateCommandBufferConfig& init_params,
1566 int32 route_id) {
1567 TRACE_EVENT1("gpu",
1568 "RenderThreadImpl::CreateViewCommandBuffer",
1569 "surface_id",
1570 surface_id);
1572 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1573 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1574 surface_id,
1575 init_params,
1576 route_id,
1577 &result);
1579 // Allow calling this from the compositor thread.
1580 thread_safe_sender()->Send(message);
1582 return result;
1585 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1586 notify_webkit_of_modal_loop_ = false;
1589 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1590 base::ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1591 RenderProcessObserver* observer;
1592 while ((observer = it.GetNext()) != NULL) {
1593 if (observer->OnControlMessageReceived(msg))
1594 return true;
1597 // Some messages are handled by delegates.
1598 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1599 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1600 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1601 return true;
1604 bool handled = true;
1605 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1606 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1607 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1608 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1609 OnSetZoomLevelForCurrentURL)
1610 // TODO(port): removed from render_messages_internal.h;
1611 // is there a new non-windows message I should add here?
1612 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1613 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1614 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1615 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1616 #if defined(OS_ANDROID)
1617 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1618 OnSetWebKitSharedTimersSuspended)
1619 #endif
1620 #if defined(OS_MACOSX)
1621 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1622 #endif
1623 #if defined(ENABLE_PLUGINS)
1624 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1625 #endif
1626 IPC_MESSAGE_UNHANDLED(handled = false)
1627 IPC_END_MESSAGE_MAP()
1628 return handled;
1631 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params) {
1632 CompositorDependencies* compositor_deps = this;
1633 RenderFrameImpl::CreateFrame(
1634 params.routing_id, params.parent_routing_id,
1635 params.previous_sibling_routing_id, params.proxy_routing_id,
1636 params.replication_state, compositor_deps, params.widget_params);
1639 void RenderThreadImpl::OnCreateNewFrameProxy(
1640 int routing_id,
1641 int parent_routing_id,
1642 int render_view_routing_id,
1643 const FrameReplicationState& replicated_state) {
1644 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1645 render_view_routing_id, replicated_state);
1648 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1649 const std::string& host,
1650 double zoom_level) {
1651 RenderViewZoomer zoomer(scheme, host, zoom_level);
1652 RenderView::ForEach(&zoomer);
1655 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1656 EnsureWebKitInitialized();
1657 CompositorDependencies* compositor_deps = this;
1658 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1659 RenderViewImpl::Create(compositor_deps, params, false);
1662 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1663 CauseForGpuLaunch cause_for_gpu_launch) {
1664 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1666 if (gpu_channel_.get()) {
1667 // Do nothing if we already have a GPU channel or are already
1668 // establishing one.
1669 if (!gpu_channel_->IsLost())
1670 return gpu_channel_.get();
1672 // Recreate the channel if it has been lost.
1673 gpu_channel_->DestroyChannel();
1674 gpu_channel_ = NULL;
1677 // Ask the browser for the channel name.
1678 int client_id = 0;
1679 IPC::ChannelHandle channel_handle;
1680 gpu::GPUInfo gpu_info;
1681 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1682 &client_id,
1683 &channel_handle,
1684 &gpu_info)) ||
1685 #if defined(OS_POSIX)
1686 channel_handle.socket.fd == -1 ||
1687 #endif
1688 channel_handle.name.empty()) {
1689 // Otherwise cancel the connection.
1690 return NULL;
1693 GetContentClient()->SetGpuInfo(gpu_info);
1695 // Cache some variables that are needed on the compositor thread for our
1696 // implementation of GpuChannelHostFactory.
1697 io_thread_task_runner_ = ChildProcess::current()->io_task_runner();
1699 gpu_channel_ =
1700 GpuChannelHost::Create(this,
1701 gpu_info,
1702 channel_handle,
1703 ChildProcess::current()->GetShutDownEvent(),
1704 gpu_memory_buffer_manager());
1705 return gpu_channel_.get();
1708 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1709 blink::WebMediaStreamCenterClient* client) {
1710 #if defined(ENABLE_WEBRTC)
1711 if (!media_stream_center_) {
1712 media_stream_center_ = GetContentClient()->renderer()
1713 ->OverrideCreateWebMediaStreamCenter(client);
1714 if (!media_stream_center_) {
1715 scoped_ptr<MediaStreamCenter> media_stream_center(
1716 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1717 media_stream_center_ = media_stream_center.release();
1720 #endif
1721 return media_stream_center_;
1724 #if defined(ENABLE_WEBRTC)
1725 PeerConnectionDependencyFactory*
1726 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1727 return peer_connection_factory_.get();
1729 #endif
1731 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1732 if (!gpu_channel_.get())
1733 return NULL;
1735 if (gpu_channel_->IsLost())
1736 return NULL;
1738 return gpu_channel_.get();
1741 #if defined(ENABLE_PLUGINS)
1742 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1743 EnsureWebKitInitialized();
1744 // The call below will cause a GetPlugins call with refresh=true, but at this
1745 // point we already know that the browser has refreshed its list, so disable
1746 // refresh temporarily to prevent each renderer process causing the list to be
1747 // regenerated.
1748 blink_platform_impl_->set_plugin_refresh_allowed(false);
1749 blink::resetPluginCache(reload_pages);
1750 blink_platform_impl_->set_plugin_refresh_allowed(true);
1752 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1754 #endif
1756 void RenderThreadImpl::OnNetworkTypeChanged(
1757 net::NetworkChangeNotifier::ConnectionType type) {
1758 EnsureWebKitInitialized();
1759 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1760 WebNetworkStateNotifier::setOnLine(online);
1761 FOR_EACH_OBSERVER(
1762 RenderProcessObserver, observers_, NetworkStateChanged(online));
1763 WebNetworkStateNotifier::setWebConnectionType(
1764 NetConnectionTypeToWebConnectionType(type));
1767 void RenderThreadImpl::OnUpdateTimezone(const std::string& zone_id) {
1768 if (!blink_platform_impl_)
1769 return;
1770 if (!zone_id.empty()) {
1771 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
1772 icu::UnicodeString::fromUTF8(zone_id));
1773 icu::TimeZone::adoptDefault(new_zone);
1774 VLOG(1) << "ICU default timezone is set to " << zone_id;
1776 NotifyTimezoneChange();
1779 #if defined(OS_ANDROID)
1780 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1781 EnsureWebKitInitialized();
1782 if (suspend) {
1783 renderer_scheduler_->SuspendTimerQueue();
1784 } else {
1785 renderer_scheduler_->ResumeTimerQueue();
1787 webkit_shared_timer_suspended_ = suspend;
1789 #endif
1791 #if defined(OS_MACOSX)
1792 void RenderThreadImpl::OnUpdateScrollbarTheme(
1793 const ViewMsg_UpdateScrollbarTheme_Params& params) {
1794 EnsureWebKitInitialized();
1795 static_cast<WebScrollbarBehaviorImpl*>(
1796 blink_platform_impl_->scrollbarBehavior())
1797 ->set_jump_on_track_click(params.jump_on_track_click);
1799 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
1800 params.initial_button_delay, params.autoscroll_button_delay,
1801 params.preferred_scroller_style, params.redraw,
1802 params.scroll_animation_enabled, params.button_placement);
1804 #endif
1806 void RenderThreadImpl::OnCreateNewSharedWorker(
1807 const WorkerProcessMsg_CreateWorker_Params& params) {
1808 // EmbeddedSharedWorkerStub will self-destruct.
1809 new EmbeddedSharedWorkerStub(params.url,
1810 params.name,
1811 params.content_security_policy,
1812 params.security_policy_type,
1813 params.pause_on_start,
1814 params.route_id);
1817 void RenderThreadImpl::OnMemoryPressure(
1818 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1819 ReleaseFreeMemory();
1821 // Do not call into blink if it is not initialized.
1822 if (blink_platform_impl_) {
1823 blink::WebCache::pruneAll();
1825 if (blink::mainThreadIsolate()) {
1826 // Trigger full v8 garbage collection on memory pressure notifications.
1827 // This will potentially hang the renderer for a long time, however, when
1828 // we receive a memory pressure notification, we might be about to be
1829 // killed.
1830 blink::mainThreadIsolate()->LowMemoryNotification();
1831 RenderThread::Get()->PostTaskToAllWebWorkers(
1832 base::Bind(&LowMemoryNotificationOnThisThread));
1835 if (memory_pressure_level ==
1836 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1837 // Clear the image cache.
1838 blink::WebImageCache::clear();
1840 // Purge Skia font cache, by setting it to 0 and then again to the
1841 // previous limit.
1842 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1843 SkGraphics::SetFontCacheLimit(font_cache_limit);
1848 scoped_refptr<base::SingleThreadTaskRunner>
1849 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1850 DCHECK(message_loop() == base::MessageLoop::current());
1851 if (!file_thread_) {
1852 file_thread_.reset(new base::Thread("Renderer::FILE"));
1853 file_thread_->Start();
1855 return file_thread_->task_runner();
1858 scoped_refptr<base::SingleThreadTaskRunner>
1859 RenderThreadImpl::GetMediaThreadTaskRunner() {
1860 DCHECK(message_loop() == base::MessageLoop::current());
1861 if (!media_thread_) {
1862 media_thread_.reset(new base::Thread("Media"));
1863 media_thread_->Start();
1865 #if defined(OS_ANDROID)
1866 renderer_demuxer_ = new RendererDemuxerAndroid();
1867 AddFilter(renderer_demuxer_.get());
1868 #endif
1870 return media_thread_->task_runner();
1873 base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
1874 return raster_worker_pool_.get();
1877 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1878 blink_platform_impl_->sampleGamepads(*data);
1881 bool RenderThreadImpl::RendererIsHidden() const {
1882 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1885 void RenderThreadImpl::WidgetCreated() {
1886 bool renderer_was_hidden = RendererIsHidden();
1887 widget_count_++;
1888 if (renderer_was_hidden)
1889 OnRendererVisible();
1892 void RenderThreadImpl::WidgetDestroyed() {
1893 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1894 // unhidden before WidgetDestroyed is called.
1895 DCHECK_GT(widget_count_, 0);
1896 DCHECK_GT(widget_count_, hidden_widget_count_);
1897 widget_count_--;
1898 if (RendererIsHidden())
1899 OnRendererHidden();
1902 void RenderThreadImpl::WidgetHidden() {
1903 DCHECK_LT(hidden_widget_count_, widget_count_);
1904 hidden_widget_count_++;
1905 if (RendererIsHidden())
1906 OnRendererHidden();
1909 void RenderThreadImpl::WidgetRestored() {
1910 bool renderer_was_hidden = RendererIsHidden();
1911 DCHECK_GT(hidden_widget_count_, 0);
1912 hidden_widget_count_--;
1913 if (renderer_was_hidden)
1914 OnRendererVisible();
1917 void RenderThreadImpl::OnRendererHidden() {
1918 renderer_scheduler_->OnRendererHidden();
1920 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1921 // scheduled by the RendererScheduler - http://crbug.com/469210.
1922 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1923 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1926 void RenderThreadImpl::OnRendererVisible() {
1927 renderer_scheduler_->OnRendererVisible();
1929 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1930 return;
1932 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1935 void RenderThreadImpl::ReleaseFreeMemory() {
1936 base::allocator::ReleaseFreeMemory();
1937 discardable_shared_memory_manager()->ReleaseFreeMemory();
1939 if (blink_platform_impl_)
1940 blink::decommitFreeableMemory();
1943 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1944 int routing_id,
1945 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1946 mojo::ServiceProviderPtr exposed_services)
1947 : routing_id_(routing_id),
1948 services_(services.Pass()),
1949 exposed_services_(exposed_services.Pass()) {
1950 // The RenderFrame may be deleted before the ExchangeServiceProviders message
1951 // is received. In that case, the RenderFrameHost should close the connection,
1952 // which is detected by setting an error handler on |exposed_services_|.
1953 exposed_services_.set_connection_error_handler(base::Bind(
1954 &RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError,
1955 base::Unretained(this)));
1958 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1961 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
1962 size_t erased =
1963 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
1964 routing_id_);
1965 DCHECK_EQ(1u, erased);
1968 } // namespace content