Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blob8b7e6425775a5c2c1607abf158ad936d72f6065d
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/trace_event.h"
33 #include "base/values.h"
34 #include "cc/base/switches.h"
35 #include "cc/blink/web_external_bitmap_impl.h"
36 #include "cc/blink/web_layer_impl.h"
37 #include "cc/raster/task_graph_runner.h"
38 #include "cc/trees/layer_tree_settings.h"
39 #include "components/scheduler/renderer/renderer_scheduler.h"
40 #include "content/child/appcache/appcache_dispatcher.h"
41 #include "content/child/appcache/appcache_frontend_impl.h"
42 #include "content/child/child_discardable_shared_memory_manager.h"
43 #include "content/child/child_gpu_memory_buffer_manager.h"
44 #include "content/child/child_histogram_message_filter.h"
45 #include "content/child/child_resource_message_filter.h"
46 #include "content/child/child_shared_bitmap_manager.h"
47 #include "content/child/content_child_helpers.h"
48 #include "content/child/db_message_filter.h"
49 #include "content/child/indexed_db/indexed_db_dispatcher.h"
50 #include "content/child/indexed_db/indexed_db_message_filter.h"
51 #include "content/child/npapi/npobject_util.h"
52 #include "content/child/plugin_messages.h"
53 #include "content/child/resource_dispatcher.h"
54 #include "content/child/resource_scheduling_filter.h"
55 #include "content/child/runtime_features.h"
56 #include "content/child/thread_safe_sender.h"
57 #include "content/child/web_database_observer_impl.h"
58 #include "content/child/worker_task_runner.h"
59 #include "content/common/child_process_messages.h"
60 #include "content/common/content_constants_internal.h"
61 #include "content/common/database_messages.h"
62 #include "content/common/dom_storage/dom_storage_messages.h"
63 #include "content/common/frame_messages.h"
64 #include "content/common/gpu/client/context_provider_command_buffer.h"
65 #include "content/common/gpu/client/gpu_channel_host.h"
66 #include "content/common/gpu/gpu_messages.h"
67 #include "content/common/gpu/gpu_process_launch_causes.h"
68 #include "content/common/render_frame_setup.mojom.h"
69 #include "content/common/resource_messages.h"
70 #include "content/common/service_worker/embedded_worker_setup.mojom.h"
71 #include "content/common/view_messages.h"
72 #include "content/common/worker_messages.h"
73 #include "content/public/common/content_constants.h"
74 #include "content/public/common/content_paths.h"
75 #include "content/public/common/content_switches.h"
76 #include "content/public/common/mojo_channel_switches.h"
77 #include "content/public/common/renderer_preferences.h"
78 #include "content/public/common/url_constants.h"
79 #include "content/public/renderer/content_renderer_client.h"
80 #include "content/public/renderer/render_process_observer.h"
81 #include "content/public/renderer/render_view_visitor.h"
82 #include "content/renderer/bluetooth/bluetooth_message_filter.h"
83 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
84 #include "content/renderer/cache_storage/cache_storage_dispatcher.h"
85 #include "content/renderer/cache_storage/cache_storage_message_filter.h"
86 #include "content/renderer/devtools/devtools_agent_filter.h"
87 #include "content/renderer/devtools/v8_sampling_profiler.h"
88 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
89 #include "content/renderer/dom_storage/webstoragearea_impl.h"
90 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
91 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
92 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
93 #include "content/renderer/gpu/compositor_output_surface.h"
94 #include "content/renderer/input/input_event_filter.h"
95 #include "content/renderer/input/input_handler_manager.h"
96 #include "content/renderer/input/main_thread_input_event_filter.h"
97 #include "content/renderer/media/aec_dump_message_filter.h"
98 #include "content/renderer/media/audio_input_message_filter.h"
99 #include "content/renderer/media/audio_message_filter.h"
100 #include "content/renderer/media/audio_renderer_mixer_manager.h"
101 #include "content/renderer/media/media_stream_center.h"
102 #include "content/renderer/media/midi_message_filter.h"
103 #include "content/renderer/media/render_media_client.h"
104 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
105 #include "content/renderer/media/video_capture_impl_manager.h"
106 #include "content/renderer/media/video_capture_message_filter.h"
107 #include "content/renderer/net_info_helper.h"
108 #include "content/renderer/p2p/socket_dispatcher.h"
109 #include "content/renderer/render_frame_proxy.h"
110 #include "content/renderer/render_process_impl.h"
111 #include "content/renderer/render_view_impl.h"
112 #include "content/renderer/renderer_blink_platform_impl.h"
113 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
114 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
115 #include "content/renderer/service_worker/service_worker_context_client.h"
116 #include "content/renderer/service_worker/service_worker_context_message_filter.h"
117 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
118 #include "gin/public/debug.h"
119 #include "gpu/GLES2/gl2extchromium.h"
120 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
121 #include "ipc/ipc_channel_handle.h"
122 #include "ipc/ipc_platform_file.h"
123 #include "ipc/mojo/ipc_channel_mojo.h"
124 #include "media/base/audio_hardware_config.h"
125 #include "media/base/media.h"
126 #include "media/renderers/gpu_video_accelerator_factories.h"
127 #include "mojo/common/common_type_converters.h"
128 #include "net/base/net_errors.h"
129 #include "net/base/port_util.h"
130 #include "skia/ext/event_tracer_impl.h"
131 #include "third_party/WebKit/public/platform/WebString.h"
132 #include "third_party/WebKit/public/platform/WebThread.h"
133 #include "third_party/WebKit/public/web/WebCache.h"
134 #include "third_party/WebKit/public/web/WebColorName.h"
135 #include "third_party/WebKit/public/web/WebDatabase.h"
136 #include "third_party/WebKit/public/web/WebDocument.h"
137 #include "third_party/WebKit/public/web/WebFrame.h"
138 #include "third_party/WebKit/public/web/WebImageCache.h"
139 #include "third_party/WebKit/public/web/WebKit.h"
140 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
141 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
142 #include "third_party/WebKit/public/web/WebScriptController.h"
143 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
144 #include "third_party/WebKit/public/web/WebView.h"
145 #include "third_party/icu/source/i18n/unicode/timezone.h"
146 #include "third_party/mojo/src/mojo/public/cpp/bindings/strong_binding.h"
147 #include "third_party/skia/include/core/SkGraphics.h"
148 #include "ui/base/layout.h"
149 #include "ui/base/ui_base_switches.h"
150 #include "v8/include/v8.h"
152 #if defined(OS_ANDROID)
153 #include <cpu-features.h>
154 #include "content/renderer/android/synchronous_compositor_factory.h"
155 #include "content/renderer/media/android/renderer_demuxer_android.h"
156 #endif
158 #if defined(OS_MACOSX)
159 #include "base/mac/mac_util.h"
160 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
161 #endif
163 #if defined(OS_POSIX)
164 #include "ipc/ipc_channel_posix.h"
165 #endif
167 #if defined(OS_WIN)
168 #include <windows.h>
169 #include <objbase.h>
170 #else
171 // TODO(port)
172 #include "content/child/npapi/np_channel_base.h"
173 #endif
175 #if defined(ENABLE_PLUGINS)
176 #include "content/renderer/npapi/plugin_channel_host.h"
177 #endif
179 #if defined(ENABLE_WEBRTC)
180 #include "content/renderer/media/peer_connection_tracker.h"
181 #include "content/renderer/media/rtc_peer_connection_handler.h"
182 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
183 #include "content/renderer/media/webrtc_identity_service.h"
184 #endif
186 #ifdef ENABLE_VTUNE_JIT_INTERFACE
187 #include "v8/src/third_party/vtune/v8-vtune.h"
188 #endif
190 using base::ThreadRestrictions;
191 using blink::WebDocument;
192 using blink::WebFrame;
193 using blink::WebNetworkStateNotifier;
194 using blink::WebRuntimeFeatures;
195 using blink::WebScriptController;
196 using blink::WebSecurityPolicy;
197 using blink::WebString;
198 using blink::WebView;
200 namespace content {
202 namespace {
204 const int64 kInitialIdleHandlerDelayMs = 1000;
205 const int64 kLongIdleHandlerDelayMs = 30*1000;
207 #if defined(OS_ANDROID)
208 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
209 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
210 // induced work takes but a fraction (~1/4) of the overall frame budget.
211 const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
212 #else
213 const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
214 #endif
215 const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
217 // Maximum allocation size allowed for image scaling filters that
218 // require pre-scaling. Skia will fallback to a filter that doesn't
219 // require pre-scaling if the default filter would require an
220 // allocation that exceeds this limit.
221 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
223 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
224 // incorrectly from the wrong thread.
225 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
226 lazy_tls = LAZY_INSTANCE_INITIALIZER;
228 class RenderViewZoomer : public RenderViewVisitor {
229 public:
230 RenderViewZoomer(const std::string& scheme,
231 const std::string& host,
232 double zoom_level) : scheme_(scheme),
233 host_(host),
234 zoom_level_(zoom_level) {
237 bool Visit(RenderView* render_view) override {
238 WebView* webview = render_view->GetWebView();
239 // Remote frames don't host documents.
240 // TODO(wjmaclean) Although it seems likely that a frame without a
241 // document can safely early-out here, we should confirm this is truly
242 // the case. https://crbug.com/477007
243 if (webview->mainFrame()->isWebRemoteFrame())
244 return true;
246 WebDocument document = webview->mainFrame()->document();
248 // Don't set zoom level for full-page plugin since they don't use the same
249 // zoom settings.
250 if (document.isPluginDocument())
251 return true;
252 GURL url(document.url());
253 // Empty scheme works as wildcard that matches any scheme,
254 if ((net::GetHostOrSpecFromURL(url) == host_) &&
255 (scheme_.empty() || scheme_ == url.scheme()) &&
256 !static_cast<RenderViewImpl*>(render_view)
257 ->uses_temporary_zoom_level()) {
258 webview->hidePopups();
259 webview->setZoomLevel(zoom_level_);
261 return true;
264 private:
265 const std::string scheme_;
266 const std::string host_;
267 const double zoom_level_;
269 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
272 std::string HostToCustomHistogramSuffix(const std::string& host) {
273 if (host == "mail.google.com")
274 return ".gmail";
275 if (host == "docs.google.com" || host == "drive.google.com")
276 return ".docs";
277 if (host == "plus.google.com")
278 return ".plus";
279 if (host == "inbox.google.com")
280 return ".inbox";
281 return std::string();
284 void* CreateHistogram(
285 const char *name, int min, int max, size_t buckets) {
286 if (min <= 0)
287 min = 1;
288 std::string histogram_name;
289 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
290 if (render_thread_impl) { // Can be null in tests.
291 histogram_name = render_thread_impl->
292 histogram_customizer()->ConvertToCustomHistogramName(name);
293 } else {
294 histogram_name = std::string(name);
296 base::HistogramBase* histogram = base::Histogram::FactoryGet(
297 histogram_name, min, max, buckets,
298 base::Histogram::kUmaTargetedHistogramFlag);
299 return histogram;
302 void AddHistogramSample(void* hist, int sample) {
303 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
304 histogram->Add(sample);
307 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
308 const gfx::Size& size) {
309 return ChildThreadImpl::current()->shared_bitmap_manager()->
310 AllocateSharedBitmap(size);
313 void EnableBlinkPlatformLogChannels(const std::string& channels) {
314 if (channels.empty())
315 return;
316 base::StringTokenizer t(channels, ", ");
317 while (t.GetNext())
318 blink::enableLogChannel(t.token().c_str());
321 void NotifyTimezoneChangeOnThisThread() {
322 v8::Isolate* isolate = v8::Isolate::GetCurrent();
323 if (!isolate)
324 return;
325 v8::Date::DateTimeConfigurationChangeNotification(isolate);
328 void LowMemoryNotificationOnThisThread() {
329 v8::Isolate* isolate = v8::Isolate::GetCurrent();
330 if (!isolate)
331 return;
332 isolate->LowMemoryNotification();
335 class RenderFrameSetupImpl : public RenderFrameSetup {
336 public:
337 explicit RenderFrameSetupImpl(
338 mojo::InterfaceRequest<RenderFrameSetup> request)
339 : routing_id_highmark_(-1), binding_(this, request.Pass()) {}
341 void ExchangeServiceProviders(
342 int32_t frame_routing_id,
343 mojo::InterfaceRequest<mojo::ServiceProvider> services,
344 mojo::ServiceProviderPtr exposed_services)
345 override {
346 // TODO(morrita): This is for investigating http://crbug.com/415059 and
347 // should be removed once it is fixed.
348 CHECK_LT(routing_id_highmark_, frame_routing_id);
349 routing_id_highmark_ = frame_routing_id;
351 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
352 // We can receive a GetServiceProviderForFrame message for a frame not yet
353 // created due to a race between the message and a ViewMsg_New IPC that
354 // triggers creation of the RenderFrame we want.
355 if (!frame) {
356 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
357 frame_routing_id, services.Pass(), exposed_services.Pass());
358 return;
361 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
364 private:
365 int32_t routing_id_highmark_;
366 mojo::StrongBinding<RenderFrameSetup> binding_;
369 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
370 new RenderFrameSetupImpl(request.Pass());
373 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
374 blink::WebGraphicsContext3D::Attributes attributes;
375 attributes.shareResources = true;
376 attributes.depth = false;
377 attributes.stencil = false;
378 attributes.antialias = false;
379 attributes.noAutomaticFlushes = true;
380 return attributes;
383 void SetupEmbeddedWorkerOnWorkerThread(
384 mojo::InterfaceRequest<mojo::ServiceProvider> services,
385 mojo::ServiceProviderPtr exposed_services) {
386 ServiceWorkerContextClient* client =
387 ServiceWorkerContextClient::ThreadSpecificInstance();
388 // It is possible for client to be null if for some reason the worker died
389 // before this call made it to the worker thread. In that case just do
390 // nothing and let mojo close the connection.
391 if (!client)
392 return;
393 client->BindServiceRegistry(services.Pass(), exposed_services.Pass());
396 class EmbeddedWorkerSetupImpl : public EmbeddedWorkerSetup {
397 public:
398 explicit EmbeddedWorkerSetupImpl(
399 mojo::InterfaceRequest<EmbeddedWorkerSetup> request)
400 : binding_(this, request.Pass()) {}
402 void ExchangeServiceProviders(
403 int32_t thread_id,
404 mojo::InterfaceRequest<mojo::ServiceProvider> services,
405 mojo::ServiceProviderPtr exposed_services) override {
406 WorkerTaskRunner::Instance()->GetTaskRunnerFor(thread_id)->PostTask(
407 FROM_HERE,
408 base::Bind(&SetupEmbeddedWorkerOnWorkerThread, base::Passed(&services),
409 base::Passed(&exposed_services)));
412 private:
413 mojo::StrongBinding<EmbeddedWorkerSetup> binding_;
416 void CreateEmbeddedWorkerSetup(
417 mojo::InterfaceRequest<EmbeddedWorkerSetup> request) {
418 new EmbeddedWorkerSetupImpl(request.Pass());
421 } // namespace
423 class RasterWorkerPool : public base::SequencedTaskRunner,
424 public base::DelegateSimpleThread::Delegate {
425 public:
426 RasterWorkerPool()
427 : namespace_token_(task_graph_runner_.GetNamespaceToken()) {}
429 void Start(int num_threads,
430 const base::SimpleThread::Options& thread_options) {
431 DCHECK(threads_.empty());
432 while (threads_.size() < static_cast<size_t>(num_threads)) {
433 scoped_ptr<base::DelegateSimpleThread> thread(
434 new base::DelegateSimpleThread(
435 this, base::StringPrintf(
436 "CompositorTileWorker%u",
437 static_cast<unsigned>(threads_.size() + 1)).c_str(),
438 thread_options));
439 thread->Start();
440 threads_.push_back(thread.Pass());
444 void Shutdown() {
445 // Shutdown raster threads.
446 task_graph_runner_.Shutdown();
447 while (!threads_.empty()) {
448 threads_.back()->Join();
449 threads_.pop_back();
453 // Overridden from base::TaskRunner:
454 bool PostDelayedTask(const tracked_objects::Location& from_here,
455 const base::Closure& task,
456 base::TimeDelta delay) override {
457 return PostNonNestableDelayedTask(from_here, task, delay);
460 bool RunsTasksOnCurrentThread() const override { return true; }
462 // Overridden from base::SequencedTaskRunner:
463 bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
464 const base::Closure& task,
465 base::TimeDelta delay) override {
466 base::AutoLock lock(lock_);
467 DCHECK(!threads_.empty());
469 // Remove completed tasks.
470 DCHECK(completed_tasks_.empty());
471 task_graph_runner_.CollectCompletedTasks(namespace_token_,
472 &completed_tasks_);
473 DCHECK_LE(completed_tasks_.size(), tasks_.size());
474 DCHECK(std::equal(completed_tasks_.begin(), completed_tasks_.end(),
475 tasks_.begin()));
476 tasks_.erase(tasks_.begin(), tasks_.begin() + completed_tasks_.size());
477 completed_tasks_.clear();
479 tasks_.push_back(make_scoped_refptr(new ClosureTask(task)));
481 graph_.Reset();
482 for (const auto& task : tasks_) {
483 cc::TaskGraph::Node node(task.get(), 0, graph_.nodes.size());
484 if (graph_.nodes.size()) {
485 graph_.edges.push_back(
486 cc::TaskGraph::Edge(graph_.nodes.back().task, node.task));
488 graph_.nodes.push_back(node);
491 task_graph_runner_.ScheduleTasks(namespace_token_, &graph_);
492 return true;
495 // Overridden from base::DelegateSimpleThread::Delegate:
496 void Run() override { task_graph_runner_.Run(); }
498 cc::TaskGraphRunner* GetTaskGraphRunner() { return &task_graph_runner_; }
500 protected:
501 ~RasterWorkerPool() override {}
503 private:
504 // Simple Task for the TaskGraphRunner that wraps a closure.
505 class ClosureTask : public cc::Task {
506 public:
507 ClosureTask(const base::Closure& closure) : closure_(closure) {}
509 // Overridden from cc::Task:
510 void RunOnWorkerThread() override {
511 closure_.Run();
512 closure_.Reset();
515 protected:
516 ~ClosureTask() override {}
518 private:
519 base::Closure closure_;
521 DISALLOW_COPY_AND_ASSIGN(ClosureTask);
524 // The actual threads where work is done.
525 ScopedVector<base::DelegateSimpleThread> threads_;
526 cc::TaskGraphRunner task_graph_runner_;
528 // Namespace where the SequencedTaskRunner tasks run.
529 const cc::NamespaceToken namespace_token_;
531 // Lock to exclusively access all the following members that are used to
532 // implement the SequencedTaskRunner interface.
533 base::Lock lock_;
534 // List of tasks currently queued up for execution.
535 ClosureTask::Vector tasks_;
536 // Cached vector to avoid allocation when getting the list of complete tasks.
537 ClosureTask::Vector completed_tasks_;
538 // Graph object used for scheduling tasks.
539 cc::TaskGraph graph_;
542 // For measuring memory usage after each task. Behind a command line flag.
543 class MemoryObserver : public base::MessageLoop::TaskObserver {
544 public:
545 MemoryObserver() {}
546 ~MemoryObserver() override {}
548 void WillProcessTask(const base::PendingTask& pending_task) override {}
550 void DidProcessTask(const base::PendingTask& pending_task) override {
551 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
554 private:
555 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
558 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
559 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
560 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
561 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
564 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
566 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
567 const std::string& host, size_t view_count) {
568 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
569 switches::kDisableHistogramCustomizer)) {
570 return;
572 // Check if all RenderViews are displaying a page from the same host. If there
573 // is only one RenderView, the common host is this view's host. If there are
574 // many, check if this one shares the common host of the other
575 // RenderViews. It's ok to not detect some cases where the RenderViews share a
576 // common host. This information is only used for producing custom histograms.
577 if (view_count == 1)
578 SetCommonHost(host);
579 else if (host != common_host_)
580 SetCommonHost(std::string());
583 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
584 const char* histogram_name) const {
585 std::string name(histogram_name);
586 if (!common_host_histogram_suffix_.empty() &&
587 custom_histograms_.find(name) != custom_histograms_.end())
588 name += common_host_histogram_suffix_;
589 return name;
592 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
593 const std::string& host) {
594 if (host != common_host_) {
595 common_host_ = host;
596 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
597 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
601 // static
602 RenderThreadImpl* RenderThreadImpl::Create(
603 const InProcessChildThreadParams& params) {
604 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler =
605 scheduler::RendererScheduler::Create();
606 return new RenderThreadImpl(params, renderer_scheduler.Pass());
609 // static
610 RenderThreadImpl* RenderThreadImpl::Create(
611 scoped_ptr<base::MessageLoop> main_message_loop,
612 scoped_ptr<scheduler::RendererScheduler> renderer_scheduler) {
613 return new RenderThreadImpl(main_message_loop.Pass(),
614 renderer_scheduler.Pass());
617 RenderThreadImpl* RenderThreadImpl::current() {
618 return lazy_tls.Pointer()->Get();
621 RenderThreadImpl::RenderThreadImpl(
622 const InProcessChildThreadParams& params,
623 scoped_ptr<scheduler::RendererScheduler> scheduler)
624 : ChildThreadImpl(Options::Builder()
625 .InBrowserProcess(params)
626 .UseMojoChannel(ShouldUseMojoChannel())
627 .Build()),
628 renderer_scheduler_(scheduler.Pass()),
629 raster_worker_pool_(new RasterWorkerPool()) {
630 Init();
633 // When we run plugins in process, we actually run them on the render thread,
634 // which means that we need to make the render thread pump UI events.
635 RenderThreadImpl::RenderThreadImpl(
636 scoped_ptr<base::MessageLoop> main_message_loop,
637 scoped_ptr<scheduler::RendererScheduler> scheduler)
638 : ChildThreadImpl(Options::Builder()
639 .UseMojoChannel(ShouldUseMojoChannel())
640 .Build()),
641 renderer_scheduler_(scheduler.Pass()),
642 main_message_loop_(main_message_loop.Pass()),
643 raster_worker_pool_(new RasterWorkerPool()) {
644 Init();
647 void RenderThreadImpl::Init() {
648 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
650 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
651 base::PlatformThread::CurrentId(),
652 kTraceEventRendererMainThreadSortIndex);
654 #if defined(OS_MACOSX) || defined(OS_ANDROID)
655 // On Mac and Android, the select popups are rendered by the browser.
656 blink::WebView::setUseExternalPopupMenus(true);
657 #endif
659 lazy_tls.Pointer()->Set(this);
661 // Register this object as the main thread.
662 ChildProcess::current()->set_main_thread(this);
664 // In single process the single process is all there is.
665 notify_webkit_of_modal_loop_ = true;
666 webkit_shared_timer_suspended_ = false;
667 widget_count_ = 0;
668 hidden_widget_count_ = 0;
669 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
670 idle_notifications_to_skip_ = 0;
671 layout_test_mode_ = false;
673 appcache_dispatcher_.reset(
674 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
675 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
676 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
677 thread_safe_sender()));
678 main_thread_cache_storage_dispatcher_.reset(
679 new CacheStorageDispatcher(thread_safe_sender()));
680 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
682 // Note: This may reorder messages from the ResourceDispatcher with respect to
683 // other subsystems.
684 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
685 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
686 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
687 kMaxResourceRequestsPerFlushWhenThrottled));
688 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
690 media_stream_center_ = NULL;
692 db_message_filter_ = new DBMessageFilter();
693 AddFilter(db_message_filter_.get());
695 vc_manager_.reset(new VideoCaptureImplManager());
696 AddFilter(vc_manager_->video_capture_message_filter());
698 browser_plugin_manager_.reset(new BrowserPluginManager());
699 AddObserver(browser_plugin_manager_.get());
701 #if defined(ENABLE_WEBRTC)
702 peer_connection_tracker_.reset(new PeerConnectionTracker());
703 AddObserver(peer_connection_tracker_.get());
705 p2p_socket_dispatcher_ =
706 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
707 AddFilter(p2p_socket_dispatcher_.get());
709 webrtc_identity_service_.reset(new WebRTCIdentityService());
711 aec_dump_message_filter_ = new AecDumpMessageFilter(
712 GetIOMessageLoopProxy(), message_loop()->task_runner());
713 AddFilter(aec_dump_message_filter_.get());
715 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
716 p2p_socket_dispatcher_.get()));
717 #endif // defined(ENABLE_WEBRTC)
719 audio_input_message_filter_ =
720 new AudioInputMessageFilter(GetIOMessageLoopProxy());
721 AddFilter(audio_input_message_filter_.get());
723 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
724 AddFilter(audio_message_filter_.get());
726 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
727 AddFilter(midi_message_filter_.get());
729 bluetooth_message_filter_ = new BluetoothMessageFilter(thread_safe_sender());
730 AddFilter(bluetooth_message_filter_->GetFilter());
732 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
734 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
736 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
738 GetContentClient()->renderer()->RenderThreadStarted();
740 InitSkiaEventTracer();
742 const base::CommandLine& command_line =
743 *base::CommandLine::ForCurrentProcess();
745 cc::LayerSettings layer_settings;
746 if (command_line.HasSwitch(switches::kEnableCompositorAnimationTimelines))
747 layer_settings.use_compositor_animation_timelines = true;
748 cc_blink::WebLayerImpl::SetLayerSettings(layer_settings);
750 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
751 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
753 #if defined(OS_MACOSX) && !defined(OS_IOS)
754 is_elastic_overscroll_enabled_ = base::mac::IsOSLionOrLater();
755 if (is_elastic_overscroll_enabled_) {
756 base::ScopedCFTypeRef<CFStringRef> key(
757 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
758 Boolean key_exists = false;
759 Boolean value = CFPreferencesGetAppBooleanValue(
760 key, kCFPreferencesCurrentApplication, &key_exists);
761 if (key_exists && !value)
762 is_elastic_overscroll_enabled_ = false;
764 #else
765 is_elastic_overscroll_enabled_ = false;
766 #endif
768 std::string image_texture_target_string =
769 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
770 bool parsed_image_texture_target = base::StringToUint(
771 image_texture_target_string, &use_image_texture_target_);
772 DCHECK(parsed_image_texture_target);
774 if (command_line.HasSwitch(switches::kDisableLCDText)) {
775 is_lcd_text_enabled_ = false;
776 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
777 is_lcd_text_enabled_ = true;
778 } else {
779 #if defined(OS_ANDROID)
780 is_lcd_text_enabled_ = false;
781 #else
782 is_lcd_text_enabled_ = true;
783 #endif
786 is_gpu_rasterization_enabled_ =
787 command_line.HasSwitch(switches::kEnableGpuRasterization);
788 is_gpu_rasterization_forced_ =
789 command_line.HasSwitch(switches::kForceGpuRasterization);
791 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
792 std::string string_value = command_line.GetSwitchValueASCII(
793 switches::kGpuRasterizationMSAASampleCount);
794 bool parsed_msaa_sample_count =
795 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
796 DCHECK(parsed_msaa_sample_count) << string_value;
797 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
798 } else {
799 gpu_rasterization_msaa_sample_count_ = 0;
802 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
803 is_distance_field_text_enabled_ = false;
804 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
805 is_distance_field_text_enabled_ = true;
806 } else {
807 is_distance_field_text_enabled_ = false;
810 // Note that under Linux, the media library will normally already have
811 // been initialized by the Zygote before this instance became a Renderer.
812 media::InitializeMediaLibrary();
814 memory_pressure_listener_.reset(new base::MemoryPressureListener(
815 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
817 is_gather_pixel_refs_enabled_ = false;
819 int num_raster_threads = 0;
820 std::string string_value =
821 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
822 bool parsed_num_raster_threads =
823 base::StringToInt(string_value, &num_raster_threads);
824 DCHECK(parsed_num_raster_threads) << string_value;
825 DCHECK_GT(num_raster_threads, 0);
827 // Note: Currently, gathering of pixel refs when using a single
828 // raster thread doesn't provide any benefit. This might change
829 // in the future but we avoid it for now to reduce the cost of
830 // Picture::Create.
831 is_gather_pixel_refs_enabled_ = num_raster_threads > 1;
833 base::SimpleThread::Options thread_options;
834 #if defined(OS_ANDROID) || defined(OS_LINUX)
835 if (!command_line.HasSwitch(
836 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
837 thread_options.set_priority(base::ThreadPriority::BACKGROUND);
839 #endif
841 raster_worker_pool_->Start(num_raster_threads, thread_options);
843 // TODO(boliu): In single process, browser main loop should set up the
844 // discardable memory manager, and should skip this if kSingleProcess.
845 // See crbug.com/503724.
846 base::DiscardableMemoryAllocator::SetInstance(
847 ChildThreadImpl::discardable_shared_memory_manager());
849 service_registry()->AddService<RenderFrameSetup>(
850 base::Bind(CreateRenderFrameSetup));
851 service_registry()->AddService<EmbeddedWorkerSetup>(
852 base::Bind(CreateEmbeddedWorkerSetup));
854 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
857 RenderThreadImpl::~RenderThreadImpl() {
860 void RenderThreadImpl::Shutdown() {
861 FOR_EACH_OBSERVER(
862 RenderProcessObserver, observers_, OnRenderProcessShutdown());
864 ChildThreadImpl::Shutdown();
866 if (memory_observer_) {
867 message_loop()->RemoveTaskObserver(memory_observer_.get());
868 memory_observer_.reset();
871 // Wait for all databases to be closed.
872 if (blink_platform_impl_) {
873 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
874 // processing timer events while we're already in the process of shutting
875 // down blink, put a ScopePageLoadDeferrer on the stack.
876 WebView::willEnterModalLoop();
877 blink_platform_impl_->web_database_observer_impl()
878 ->WaitForAllDatabasesToClose();
879 WebView::didExitModalLoop();
882 // Shutdown in reverse of the initialization order.
883 if (devtools_agent_message_filter_.get()) {
884 RemoveFilter(devtools_agent_message_filter_.get());
885 devtools_agent_message_filter_ = NULL;
888 RemoveFilter(audio_input_message_filter_.get());
889 audio_input_message_filter_ = NULL;
891 #if defined(ENABLE_WEBRTC)
892 RTCPeerConnectionHandler::DestructAllHandlers();
893 // |peer_connection_factory_| cannot be deleted until after the main message
894 // loop has been destroyed. This is because there may be pending tasks that
895 // hold on to objects produced by the PC factory that depend on threads owned
896 // by the PC factory. Once those tasks have been freed, the factory can be
897 // deleted.
898 #endif
899 RemoveFilter(vc_manager_->video_capture_message_filter());
900 vc_manager_.reset();
902 RemoveFilter(db_message_filter_.get());
903 db_message_filter_ = NULL;
905 // Shutdown the file thread if it's running.
906 if (file_thread_)
907 file_thread_->Stop();
909 if (compositor_message_filter_.get()) {
910 RemoveFilter(compositor_message_filter_.get());
911 compositor_message_filter_ = NULL;
914 media_thread_.reset();
916 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
917 RemoveFilter(audio_message_filter_.get());
918 audio_message_filter_ = NULL;
920 compositor_thread_.reset();
922 raster_worker_pool_->Shutdown();
924 main_input_callback_.Cancel();
925 input_handler_manager_.reset();
926 if (input_event_filter_.get()) {
927 RemoveFilter(input_event_filter_.get());
928 input_event_filter_ = NULL;
931 // RemoveEmbeddedWorkerRoute may be called while deleting
932 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
933 // RenderThreadImpl.
934 embedded_worker_dispatcher_.reset();
936 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
937 // hold pointers to V8 objects (e.g., via pending requests).
938 main_thread_indexed_db_dispatcher_.reset();
940 main_thread_compositor_task_runner_ = NULL;
942 // Context providers must be released prior to destroying the GPU channel.
943 gpu_va_context_provider_ = nullptr;
944 shared_main_thread_contexts_ = nullptr;
946 if (gpu_channel_.get())
947 gpu_channel_->DestroyChannel();
949 // TODO(port)
950 #if defined(OS_WIN)
951 // Clean up plugin channels before this thread goes away.
952 NPChannelBase::CleanupChannels();
953 #endif
955 // Shut down the message loop and the renderer scheduler before shutting down
956 // Blink. This prevents a scenario where a pending task in the message loop
957 // accesses Blink objects after Blink shuts down.
958 // This must be at the very end of the shutdown sequence. You must not touch
959 // the message loop after this.
960 renderer_scheduler_->Shutdown();
961 main_message_loop_.reset();
962 if (blink_platform_impl_)
963 blink::shutdown();
965 lazy_tls.Pointer()->Set(NULL);
968 bool RenderThreadImpl::Send(IPC::Message* msg) {
969 // Certain synchronous messages cannot always be processed synchronously by
970 // the browser, e.g., putting up UI and waiting for the user. This could cause
971 // a complete hang of Chrome if a windowed plugin is trying to communicate
972 // with the renderer thread since the browser's UI thread could be stuck
973 // (within a Windows API call) trying to synchronously communicate with the
974 // plugin. The remedy is to pump messages on this thread while the browser
975 // is processing this request. This creates an opportunity for re-entrancy
976 // into WebKit, so we need to take care to disable callbacks, timers, and
977 // pending network loads that could trigger such callbacks.
978 bool pumping_events = false;
979 if (msg->is_sync()) {
980 if (msg->is_caller_pumping_messages()) {
981 pumping_events = true;
985 bool notify_webkit_of_modal_loop = true; // default value
986 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
988 #if defined(ENABLE_PLUGINS)
989 int render_view_id = MSG_ROUTING_NONE;
990 #endif
992 if (pumping_events) {
993 renderer_scheduler_->SuspendTimerQueue();
995 if (notify_webkit_of_modal_loop)
996 WebView::willEnterModalLoop();
997 #if defined(ENABLE_PLUGINS)
998 RenderViewImpl* render_view =
999 RenderViewImpl::FromRoutingID(msg->routing_id());
1000 if (render_view) {
1001 render_view_id = msg->routing_id();
1002 PluginChannelHost::Broadcast(
1003 new PluginMsg_SignalModalDialogEvent(render_view_id));
1005 #endif
1008 bool rv = ChildThreadImpl::Send(msg);
1010 if (pumping_events) {
1011 #if defined(ENABLE_PLUGINS)
1012 if (render_view_id != MSG_ROUTING_NONE) {
1013 PluginChannelHost::Broadcast(
1014 new PluginMsg_ResetModalDialogEvent(render_view_id));
1016 #endif
1018 if (notify_webkit_of_modal_loop)
1019 WebView::didExitModalLoop();
1021 renderer_scheduler_->ResumeTimerQueue();
1024 return rv;
1027 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
1028 return channel();
1031 std::string RenderThreadImpl::GetLocale() {
1032 // The browser process should have passed the locale to the renderer via the
1033 // --lang command line flag.
1034 const base::CommandLine& parsed_command_line =
1035 *base::CommandLine::ForCurrentProcess();
1036 const std::string& lang =
1037 parsed_command_line.GetSwitchValueASCII(switches::kLang);
1038 DCHECK(!lang.empty());
1039 return lang;
1042 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1043 return sync_message_filter();
1046 scoped_refptr<base::SingleThreadTaskRunner>
1047 RenderThreadImpl::GetIOMessageLoopProxy() {
1048 return ChildProcess::current()->io_task_runner();
1051 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
1052 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
1053 PendingRenderFrameConnectMap::iterator it =
1054 pending_render_frame_connects_.find(routing_id);
1055 if (it == pending_render_frame_connects_.end())
1056 return;
1058 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1059 if (!frame)
1060 return;
1062 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
1063 mojo::InterfaceRequest<mojo::ServiceProvider> services(
1064 connection->services().Pass());
1065 mojo::ServiceProviderPtr exposed_services(
1066 connection->exposed_services().Pass());
1067 exposed_services.set_connection_error_handler(mojo::Closure());
1068 pending_render_frame_connects_.erase(it);
1070 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
1073 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
1074 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
1077 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
1078 IPC::Listener* listener) {
1079 AddRoute(routing_id, listener);
1080 if (devtools_agent_message_filter_.get()) {
1081 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
1082 routing_id);
1086 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
1087 RemoveRoute(routing_id);
1088 if (devtools_agent_message_filter_.get()) {
1089 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
1090 routing_id);
1094 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
1095 int routing_id,
1096 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1097 mojo::ServiceProviderPtr exposed_services) {
1098 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
1099 pending_render_frame_connects_.insert(std::make_pair(
1100 routing_id,
1101 make_scoped_refptr(new PendingRenderFrameConnect(
1102 routing_id, services.Pass(), exposed_services.Pass()))));
1103 CHECK(result.second) << "Inserting a duplicate item.";
1106 int RenderThreadImpl::GenerateRoutingID() {
1107 int routing_id = MSG_ROUTING_NONE;
1108 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
1109 return routing_id;
1112 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
1113 channel()->AddFilter(filter);
1116 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
1117 channel()->RemoveFilter(filter);
1120 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
1121 observers_.AddObserver(observer);
1124 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
1125 observers_.RemoveObserver(observer);
1128 void RenderThreadImpl::SetResourceDispatcherDelegate(
1129 ResourceDispatcherDelegate* delegate) {
1130 resource_dispatcher()->set_delegate(delegate);
1133 void RenderThreadImpl::SetResourceDispatchTaskQueue(
1134 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
1135 // Add a filter that forces resource messages to be dispatched via a
1136 // particular task runner.
1137 resource_scheduling_filter_ =
1138 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
1139 channel()->AddFilter(resource_scheduling_filter_.get());
1141 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1142 // same queue to ensure tasks are executed in the expected order.
1143 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
1144 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
1147 void RenderThreadImpl::EnsureWebKitInitialized() {
1148 if (blink_platform_impl_)
1149 return;
1151 const base::CommandLine& command_line =
1152 *base::CommandLine::ForCurrentProcess();
1154 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1155 if (command_line.HasSwitch(switches::kEnableVtune))
1156 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1157 #endif
1159 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
1161 blink_platform_impl_.reset(
1162 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1163 blink::initialize(blink_platform_impl_.get());
1165 v8::Isolate* isolate = blink::mainThreadIsolate();
1166 isolate->SetCreateHistogramFunction(CreateHistogram);
1167 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1169 main_thread_compositor_task_runner_ =
1170 renderer_scheduler_->CompositorTaskRunner();
1172 main_input_callback_.Reset(
1173 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1174 base::Unretained(this)));
1176 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1178 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1179 if (enable) {
1180 #if defined(OS_ANDROID)
1181 if (SynchronousCompositorFactory* factory =
1182 SynchronousCompositorFactory::GetInstance())
1183 compositor_task_runner_ = factory->GetCompositorTaskRunner();
1184 #endif
1185 if (!compositor_task_runner_.get()) {
1186 compositor_thread_.reset(new base::Thread("Compositor"));
1187 base::Thread::Options compositor_thread_options;
1188 #if defined(OS_ANDROID)
1189 compositor_thread_options.priority = base::ThreadPriority::DISPLAY;
1190 #endif
1191 compositor_thread_->StartWithOptions(compositor_thread_options);
1192 compositor_task_runner_ = compositor_thread_->task_runner();
1193 compositor_task_runner_->PostTask(
1194 FROM_HERE,
1195 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1196 false));
1199 InputHandlerManagerClient* input_handler_manager_client = NULL;
1200 #if defined(OS_ANDROID)
1201 if (SynchronousCompositorFactory* factory =
1202 SynchronousCompositorFactory::GetInstance()) {
1203 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1205 #endif
1206 if (!input_handler_manager_client) {
1207 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1208 new InputEventFilter(main_input_callback_.callback(),
1209 main_thread_compositor_task_runner_,
1210 compositor_task_runner_));
1211 input_handler_manager_client = compositor_input_event_filter.get();
1212 input_event_filter_ = compositor_input_event_filter;
1214 input_handler_manager_.reset(new InputHandlerManager(
1215 compositor_task_runner_, input_handler_manager_client,
1216 renderer_scheduler_.get()));
1219 if (!input_event_filter_.get()) {
1220 // Always provide an input event filter implementation to ensure consistent
1221 // input event scheduling and prioritization.
1222 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1223 // MainThreadInputEventFilter, crbug.com/436057.
1224 input_event_filter_ = new MainThreadInputEventFilter(
1225 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1227 AddFilter(input_event_filter_.get());
1229 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
1230 if (enable)
1231 compositor_impl_side_task_runner = compositor_task_runner_;
1232 else
1233 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
1235 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1236 compositor_impl_side_task_runner.get());
1237 AddFilter(compositor_message_filter_.get());
1239 RenderThreadImpl::RegisterSchemes();
1241 EnableBlinkPlatformLogChannels(
1242 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1244 RenderMediaClient::Initialize();
1246 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1248 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1249 AddFilter(devtools_agent_message_filter_.get());
1251 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1253 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1254 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1256 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1258 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1259 kImageCacheSingleAllocationByteLimit);
1261 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1262 memory_observer_.reset(new MemoryObserver());
1263 message_loop()->AddTaskObserver(memory_observer_.get());
1266 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1267 std::string allowed_ports =
1268 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1269 net::SetExplicitlyAllowedPorts(allowed_ports);
1273 void RenderThreadImpl::RegisterSchemes() {
1274 // swappedout:
1275 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1276 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1277 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1279 // chrome:
1280 WebString chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme));
1281 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1282 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1283 chrome_scheme);
1284 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme);
1285 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme);
1287 // chrome-devtools:
1288 WebString devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme));
1289 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
1292 void RenderThreadImpl::NotifyTimezoneChange() {
1293 NotifyTimezoneChangeOnThisThread();
1294 RenderThread::Get()->PostTaskToAllWebWorkers(
1295 base::Bind(&NotifyTimezoneChangeOnThisThread));
1298 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1299 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1302 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1303 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1306 scoped_ptr<base::SharedMemory>
1307 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1308 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1311 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1312 return shared_bitmap_manager();
1315 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1316 WebScriptController::registerExtension(extension);
1319 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1320 idle_notification_delay_in_ms_ = initial_delay_ms;
1321 idle_timer_.Stop();
1322 idle_timer_.Start(FROM_HERE,
1323 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1324 this, &RenderThreadImpl::IdleHandler);
1327 void RenderThreadImpl::IdleHandler() {
1328 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1329 GetContentClient()->renderer()->
1330 RunIdleHandlerWhenWidgetsHidden();
1331 if (run_in_foreground_tab) {
1332 if (idle_notifications_to_skip_ > 0) {
1333 --idle_notifications_to_skip_;
1334 } else {
1335 ReleaseFreeMemory();
1337 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1338 return;
1341 ReleaseFreeMemory();
1343 // Continue the idle timer if the webkit shared timer is not suspended or
1344 // something is left to do.
1345 bool continue_timer = !webkit_shared_timer_suspended_;
1347 if (blink::mainThreadIsolate() &&
1348 !blink::mainThreadIsolate()->IdleNotificationDeadline(
1349 blink_platform_impl_->monotonicallyIncreasingTime() + 1.0)) {
1350 continue_timer = true;
1353 // Schedule next invocation. When the tab is originally hidden, an invocation
1354 // is scheduled for kInitialIdleHandlerDelayMs in
1355 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1356 // After that, idle calls can be much less frequent, so run at a maximum of
1357 // once every kLongIdleHandlerDelayMs.
1358 // Dampen the delay using the algorithm (if delay is in seconds):
1359 // delay = delay + 1 / (delay + 2)
1360 // Using floor(delay) has a dampening effect such as:
1361 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1362 // If the delay is in milliseconds, the above formula is equivalent to:
1363 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1364 // which is equivalent to
1365 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1366 if (continue_timer) {
1367 ScheduleIdleHandler(
1368 std::max(kLongIdleHandlerDelayMs,
1369 idle_notification_delay_in_ms_ +
1370 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1372 } else {
1373 idle_timer_.Stop();
1376 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1379 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1380 return idle_notification_delay_in_ms_;
1383 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1384 int64 idle_notification_delay_in_ms) {
1385 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1388 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1389 child_histogram_message_filter()->SendHistograms(sequence_number);
1392 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1393 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1396 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1397 bool result = false;
1398 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1399 return result;
1402 void RenderThreadImpl::PostponeIdleNotification() {
1403 idle_notifications_to_skip_ = 2;
1406 scoped_refptr<media::GpuVideoAcceleratorFactories>
1407 RenderThreadImpl::GetGpuFactories() {
1408 DCHECK(IsMainThread());
1410 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1412 #if defined(OS_ANDROID)
1413 if (SynchronousCompositorFactory::GetInstance()) {
1414 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1415 DLOG(WARNING) << "Accelerated video decoding is not explicitly disabled, "
1416 "but is not supported by in-process rendering";
1418 return NULL;
1420 #endif
1422 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1423 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1424 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1425 GetMediaThreadTaskRunner();
1426 if (!gpu_va_context_provider_.get() ||
1427 gpu_va_context_provider_->DestroyedOnMainThread()) {
1428 if (!gpu_channel_host.get()) {
1429 gpu_channel_host = EstablishGpuChannelSync(
1430 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1432 blink::WebGraphicsContext3D::Attributes attributes;
1433 bool lose_context_when_out_of_memory = false;
1434 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1435 make_scoped_ptr(
1436 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1437 gpu_channel_host.get(), attributes,
1438 lose_context_when_out_of_memory,
1439 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1440 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1441 NULL)),
1442 GPU_VIDEO_ACCELERATOR_CONTEXT);
1444 if (gpu_va_context_provider_.get()) {
1445 bool enable_video_accelerator =
1446 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1447 std::string image_texture_target_string =
1448 cmd_line->GetSwitchValueASCII(switches::kContentImageTextureTarget);
1449 unsigned image_texture_target = 0;
1450 bool parsed_image_texture_target =
1451 base::StringToUint(image_texture_target_string, &image_texture_target);
1452 DCHECK(parsed_image_texture_target);
1453 CHECK(gpu_channel_host.get()) << "Have gpu_va_context_provider but no "
1454 "gpu_channel_host. See crbug.com/495185.";
1455 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1456 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_,
1457 image_texture_target, enable_video_accelerator);
1459 return gpu_factories;
1462 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1463 RenderThreadImpl::CreateOffscreenContext3d() {
1464 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1465 bool lose_context_when_out_of_memory = true;
1467 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1468 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1469 return make_scoped_ptr(
1470 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1471 gpu_channel_host.get(),
1472 attributes,
1473 lose_context_when_out_of_memory,
1474 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1475 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1476 NULL));
1479 scoped_refptr<cc_blink::ContextProviderWebContext>
1480 RenderThreadImpl::SharedMainThreadContextProvider() {
1481 DCHECK(IsMainThread());
1482 if (!shared_main_thread_contexts_.get() ||
1483 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1484 shared_main_thread_contexts_ = NULL;
1485 #if defined(OS_ANDROID)
1486 SynchronousCompositorFactory* factory =
1487 SynchronousCompositorFactory::GetInstance();
1488 if (factory && factory->OverrideWithFactory()) {
1489 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1490 GetOffscreenAttribs(), "Offscreen-MainThread");
1492 #endif
1493 if (!shared_main_thread_contexts_.get()) {
1494 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1495 CreateOffscreenContext3d(), RENDERER_MAINTHREAD_CONTEXT);
1497 if (shared_main_thread_contexts_.get() &&
1498 !shared_main_thread_contexts_->BindToCurrentThread())
1499 shared_main_thread_contexts_ = NULL;
1501 return shared_main_thread_contexts_;
1504 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1505 if (!audio_renderer_mixer_manager_) {
1506 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1507 GetAudioHardwareConfig()));
1510 return audio_renderer_mixer_manager_.get();
1513 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1514 if (!audio_hardware_config_) {
1515 media::AudioParameters input_params;
1516 media::AudioParameters output_params;
1517 Send(new ViewHostMsg_GetAudioHardwareConfig(
1518 &input_params, &output_params));
1520 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1521 input_params, output_params));
1524 return audio_hardware_config_.get();
1527 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1528 return ChildProcess::current()->GetShutDownEvent();
1531 #if defined(OS_WIN)
1532 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1533 const base::string16& str) {
1534 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1537 #endif // OS_WIN
1539 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1540 return service_registry();
1543 bool RenderThreadImpl::IsGpuRasterizationForced() {
1544 return is_gpu_rasterization_forced_;
1547 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1548 return is_gpu_rasterization_enabled_;
1551 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1552 return gpu_rasterization_msaa_sample_count_;
1555 bool RenderThreadImpl::IsLcdTextEnabled() {
1556 return is_lcd_text_enabled_;
1559 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1560 return is_distance_field_text_enabled_;
1563 bool RenderThreadImpl::IsZeroCopyEnabled() {
1564 return is_zero_copy_enabled_;
1567 bool RenderThreadImpl::IsOneCopyEnabled() {
1568 return is_one_copy_enabled_;
1571 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1572 return is_elastic_overscroll_enabled_;
1575 uint32 RenderThreadImpl::GetImageTextureTarget() {
1576 return use_image_texture_target_;
1579 scoped_refptr<base::SingleThreadTaskRunner>
1580 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1581 return main_thread_compositor_task_runner_;
1584 scoped_refptr<base::SingleThreadTaskRunner>
1585 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1586 return compositor_task_runner_;
1589 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1590 return gpu_memory_buffer_manager();
1593 scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1594 return renderer_scheduler_.get();
1597 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1598 return SharedMainThreadContextProvider().get();
1601 scoped_ptr<cc::BeginFrameSource>
1602 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1603 #if defined(OS_ANDROID)
1604 if (SynchronousCompositorFactory* factory =
1605 SynchronousCompositorFactory::GetInstance()) {
1606 return factory->CreateExternalBeginFrameSource(routing_id);
1608 #endif
1609 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1610 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1613 cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
1614 return raster_worker_pool_->GetTaskGraphRunner();
1617 bool RenderThreadImpl::IsGatherPixelRefsEnabled() {
1618 return is_gather_pixel_refs_enabled_;
1621 bool RenderThreadImpl::IsMainThread() {
1622 return !!current();
1625 scoped_refptr<base::SingleThreadTaskRunner>
1626 RenderThreadImpl::GetIOThreadTaskRunner() {
1627 return io_thread_task_runner_;
1630 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1631 size_t size) {
1632 return scoped_ptr<base::SharedMemory>(
1633 HostAllocateSharedMemoryBuffer(size));
1636 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1637 int32 surface_id,
1638 const GPUCreateCommandBufferConfig& init_params,
1639 int32 route_id) {
1640 TRACE_EVENT1("gpu",
1641 "RenderThreadImpl::CreateViewCommandBuffer",
1642 "surface_id",
1643 surface_id);
1645 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1646 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1647 surface_id,
1648 init_params,
1649 route_id,
1650 &result);
1652 // Allow calling this from the compositor thread.
1653 thread_safe_sender()->Send(message);
1655 return result;
1658 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1659 notify_webkit_of_modal_loop_ = false;
1662 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1663 base::ObserverListBase<RenderProcessObserver>::Iterator it(&observers_);
1664 RenderProcessObserver* observer;
1665 while ((observer = it.GetNext()) != NULL) {
1666 if (observer->OnControlMessageReceived(msg))
1667 return true;
1670 // Some messages are handled by delegates.
1671 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1672 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1673 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1674 return true;
1677 bool handled = true;
1678 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1679 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1680 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1681 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1682 OnSetZoomLevelForCurrentURL)
1683 // TODO(port): removed from render_messages_internal.h;
1684 // is there a new non-windows message I should add here?
1685 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1686 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1687 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1688 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1689 #if defined(OS_ANDROID)
1690 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1691 OnSetWebKitSharedTimersSuspended)
1692 #endif
1693 #if defined(OS_MACOSX)
1694 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1695 #endif
1696 #if defined(ENABLE_PLUGINS)
1697 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1698 #endif
1699 IPC_MESSAGE_UNHANDLED(handled = false)
1700 IPC_END_MESSAGE_MAP()
1701 return handled;
1704 void RenderThreadImpl::OnCreateNewFrame(FrameMsg_NewFrame_Params params) {
1705 CompositorDependencies* compositor_deps = this;
1706 RenderFrameImpl::CreateFrame(
1707 params.routing_id, params.parent_routing_id,
1708 params.previous_sibling_routing_id, params.proxy_routing_id,
1709 params.replication_state, compositor_deps, params.widget_params);
1712 void RenderThreadImpl::OnCreateNewFrameProxy(
1713 int routing_id,
1714 int parent_routing_id,
1715 int render_view_routing_id,
1716 const FrameReplicationState& replicated_state) {
1717 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1718 render_view_routing_id, replicated_state);
1721 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1722 const std::string& host,
1723 double zoom_level) {
1724 RenderViewZoomer zoomer(scheme, host, zoom_level);
1725 RenderView::ForEach(&zoomer);
1728 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1729 EnsureWebKitInitialized();
1730 CompositorDependencies* compositor_deps = this;
1731 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1732 RenderViewImpl::Create(compositor_deps, params, false);
1735 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1736 CauseForGpuLaunch cause_for_gpu_launch) {
1737 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1739 if (gpu_channel_.get()) {
1740 // Do nothing if we already have a GPU channel or are already
1741 // establishing one.
1742 if (!gpu_channel_->IsLost())
1743 return gpu_channel_.get();
1745 // Recreate the channel if it has been lost.
1746 gpu_channel_->DestroyChannel();
1747 gpu_channel_ = NULL;
1750 // Ask the browser for the channel name.
1751 int client_id = 0;
1752 IPC::ChannelHandle channel_handle;
1753 gpu::GPUInfo gpu_info;
1754 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1755 &client_id,
1756 &channel_handle,
1757 &gpu_info)) ||
1758 #if defined(OS_POSIX)
1759 channel_handle.socket.fd == -1 ||
1760 #endif
1761 channel_handle.name.empty()) {
1762 // Otherwise cancel the connection.
1763 return NULL;
1766 GetContentClient()->SetGpuInfo(gpu_info);
1768 // Cache some variables that are needed on the compositor thread for our
1769 // implementation of GpuChannelHostFactory.
1770 io_thread_task_runner_ = ChildProcess::current()->io_task_runner();
1772 gpu_channel_ =
1773 GpuChannelHost::Create(this,
1774 gpu_info,
1775 channel_handle,
1776 ChildProcess::current()->GetShutDownEvent(),
1777 gpu_memory_buffer_manager());
1778 return gpu_channel_.get();
1781 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1782 blink::WebMediaStreamCenterClient* client) {
1783 #if defined(OS_ANDROID)
1784 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1785 switches::kDisableWebRTC))
1786 return NULL;
1787 #endif
1789 #if defined(ENABLE_WEBRTC)
1790 if (!media_stream_center_) {
1791 media_stream_center_ = GetContentClient()->renderer()
1792 ->OverrideCreateWebMediaStreamCenter(client);
1793 if (!media_stream_center_) {
1794 scoped_ptr<MediaStreamCenter> media_stream_center(
1795 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1796 media_stream_center_ = media_stream_center.release();
1799 #endif
1800 return media_stream_center_;
1803 #if defined(ENABLE_WEBRTC)
1804 PeerConnectionDependencyFactory*
1805 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1806 return peer_connection_factory_.get();
1808 #endif
1810 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1811 if (!gpu_channel_.get())
1812 return NULL;
1814 if (gpu_channel_->IsLost())
1815 return NULL;
1817 return gpu_channel_.get();
1820 #if defined(ENABLE_PLUGINS)
1821 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1822 EnsureWebKitInitialized();
1823 // The call below will cause a GetPlugins call with refresh=true, but at this
1824 // point we already know that the browser has refreshed its list, so disable
1825 // refresh temporarily to prevent each renderer process causing the list to be
1826 // regenerated.
1827 blink_platform_impl_->set_plugin_refresh_allowed(false);
1828 blink::resetPluginCache(reload_pages);
1829 blink_platform_impl_->set_plugin_refresh_allowed(true);
1831 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1833 #endif
1835 void RenderThreadImpl::OnNetworkTypeChanged(
1836 net::NetworkChangeNotifier::ConnectionType type) {
1837 EnsureWebKitInitialized();
1838 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1839 WebNetworkStateNotifier::setOnLine(online);
1840 FOR_EACH_OBSERVER(
1841 RenderProcessObserver, observers_, NetworkStateChanged(online));
1842 WebNetworkStateNotifier::setWebConnectionType(
1843 NetConnectionTypeToWebConnectionType(type));
1846 void RenderThreadImpl::OnUpdateTimezone(const std::string& zone_id) {
1847 if (!blink_platform_impl_)
1848 return;
1849 if (!zone_id.empty()) {
1850 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
1851 icu::UnicodeString::fromUTF8(zone_id));
1852 icu::TimeZone::adoptDefault(new_zone);
1853 VLOG(1) << "ICU default timezone is set to " << zone_id;
1855 NotifyTimezoneChange();
1858 #if defined(OS_ANDROID)
1859 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1860 EnsureWebKitInitialized();
1861 if (suspend) {
1862 renderer_scheduler_->SuspendTimerQueue();
1863 } else {
1864 renderer_scheduler_->ResumeTimerQueue();
1866 webkit_shared_timer_suspended_ = suspend;
1868 #endif
1870 #if defined(OS_MACOSX)
1871 void RenderThreadImpl::OnUpdateScrollbarTheme(
1872 const ViewMsg_UpdateScrollbarTheme_Params& params) {
1873 EnsureWebKitInitialized();
1874 static_cast<WebScrollbarBehaviorImpl*>(
1875 blink_platform_impl_->scrollbarBehavior())
1876 ->set_jump_on_track_click(params.jump_on_track_click);
1878 blink::WebScrollbarTheme::updateScrollbars(
1879 params.initial_button_delay, params.autoscroll_button_delay,
1880 params.preferred_scroller_style, params.redraw);
1882 #endif
1884 void RenderThreadImpl::OnCreateNewSharedWorker(
1885 const WorkerProcessMsg_CreateWorker_Params& params) {
1886 // EmbeddedSharedWorkerStub will self-destruct.
1887 new EmbeddedSharedWorkerStub(params.url,
1888 params.name,
1889 params.content_security_policy,
1890 params.security_policy_type,
1891 params.pause_on_start,
1892 params.route_id);
1895 void RenderThreadImpl::OnMemoryPressure(
1896 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1897 ReleaseFreeMemory();
1899 // Do not call into blink if it is not initialized.
1900 if (blink_platform_impl_) {
1901 blink::WebCache::pruneAll();
1903 if (blink::mainThreadIsolate()) {
1904 // Trigger full v8 garbage collection on memory pressure notifications.
1905 // This will potentially hang the renderer for a long time, however, when
1906 // we receive a memory pressure notification, we might be about to be
1907 // killed.
1908 blink::mainThreadIsolate()->LowMemoryNotification();
1909 RenderThread::Get()->PostTaskToAllWebWorkers(
1910 base::Bind(&LowMemoryNotificationOnThisThread));
1913 if (memory_pressure_level ==
1914 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1915 // Clear the image cache.
1916 blink::WebImageCache::clear();
1918 // Purge Skia font cache, by setting it to 0 and then again to the
1919 // previous limit.
1920 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1921 SkGraphics::SetFontCacheLimit(font_cache_limit);
1926 scoped_refptr<base::SingleThreadTaskRunner>
1927 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1928 DCHECK(message_loop() == base::MessageLoop::current());
1929 if (!file_thread_) {
1930 file_thread_.reset(new base::Thread("Renderer::FILE"));
1931 file_thread_->Start();
1933 return file_thread_->task_runner();
1936 scoped_refptr<base::SingleThreadTaskRunner>
1937 RenderThreadImpl::GetMediaThreadTaskRunner() {
1938 DCHECK(message_loop() == base::MessageLoop::current());
1939 if (!media_thread_) {
1940 media_thread_.reset(new base::Thread("Media"));
1941 media_thread_->Start();
1943 #if defined(OS_ANDROID)
1944 renderer_demuxer_ = new RendererDemuxerAndroid();
1945 AddFilter(renderer_demuxer_.get());
1946 #endif
1948 return media_thread_->task_runner();
1951 base::SequencedTaskRunner* RenderThreadImpl::GetWorkerSequencedTaskRunner() {
1952 return raster_worker_pool_.get();
1955 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1956 blink_platform_impl_->sampleGamepads(*data);
1959 bool RenderThreadImpl::RendererIsHidden() const {
1960 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
1963 void RenderThreadImpl::WidgetCreated() {
1964 bool renderer_was_hidden = RendererIsHidden();
1965 widget_count_++;
1966 if (renderer_was_hidden)
1967 OnRendererVisible();
1970 void RenderThreadImpl::WidgetDestroyed() {
1971 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
1972 // unhidden before WidgetDestroyed is called.
1973 DCHECK_GT(widget_count_, 0);
1974 DCHECK_GT(widget_count_, hidden_widget_count_);
1975 widget_count_--;
1976 if (RendererIsHidden())
1977 OnRendererHidden();
1980 void RenderThreadImpl::WidgetHidden() {
1981 DCHECK_LT(hidden_widget_count_, widget_count_);
1982 hidden_widget_count_++;
1983 if (RendererIsHidden())
1984 OnRendererHidden();
1987 void RenderThreadImpl::WidgetRestored() {
1988 bool renderer_was_hidden = RendererIsHidden();
1989 DCHECK_GT(hidden_widget_count_, 0);
1990 hidden_widget_count_--;
1991 if (renderer_was_hidden)
1992 OnRendererVisible();
1995 void RenderThreadImpl::OnRendererHidden() {
1996 renderer_scheduler_->OnRendererHidden();
1998 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1999 // scheduled by the RendererScheduler - http://crbug.com/469210.
2000 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2001 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
2004 void RenderThreadImpl::OnRendererVisible() {
2005 renderer_scheduler_->OnRendererVisible();
2007 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2008 return;
2010 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2013 void RenderThreadImpl::ReleaseFreeMemory() {
2014 base::allocator::ReleaseFreeMemory();
2015 discardable_shared_memory_manager()->ReleaseFreeMemory();
2017 if (blink_platform_impl_)
2018 blink::decommitFreeableMemory();
2021 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
2022 int routing_id,
2023 mojo::InterfaceRequest<mojo::ServiceProvider> services,
2024 mojo::ServiceProviderPtr exposed_services)
2025 : routing_id_(routing_id),
2026 services_(services.Pass()),
2027 exposed_services_(exposed_services.Pass()) {
2028 // The RenderFrame may be deleted before the ExchangeServiceProviders message
2029 // is received. In that case, the RenderFrameHost should close the connection,
2030 // which is detected by setting an error handler on |exposed_services_|.
2031 exposed_services_.set_connection_error_handler(base::Bind(
2032 &RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError,
2033 base::Unretained(this)));
2036 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
2039 void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() {
2040 size_t erased =
2041 RenderThreadImpl::current()->pending_render_frame_connects_.erase(
2042 routing_id_);
2043 DCHECK_EQ(1u, erased);
2046 } // namespace content