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"
12 #include "base/allocator/allocator_extension.h"
13 #include "base/command_line.h"
14 #include "base/debug/trace_event.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/memory/discardable_memory.h"
18 #include "base/memory/discardable_memory_emulated.h"
19 #include "base/memory/discardable_memory_shmem_allocator.h"
20 #include "base/memory/shared_memory.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/metrics/stats_table.h"
24 #include "base/path_service.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/strings/string16.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_tokenizer.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/threading/thread_local.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/values.h"
33 #include "cc/base/switches.h"
34 #include "cc/blink/web_external_bitmap_impl.h"
35 #include "cc/blink/web_layer_impl.h"
36 #include "cc/resources/raster_worker_pool.h"
37 #include "content/child/appcache/appcache_dispatcher.h"
38 #include "content/child/appcache/appcache_frontend_impl.h"
39 #include "content/child/child_discardable_shared_memory_manager.h"
40 #include "content/child/child_gpu_memory_buffer_manager.h"
41 #include "content/child/child_histogram_message_filter.h"
42 #include "content/child/content_child_helpers.h"
43 #include "content/child/db_message_filter.h"
44 #include "content/child/indexed_db/indexed_db_dispatcher.h"
45 #include "content/child/indexed_db/indexed_db_message_filter.h"
46 #include "content/child/npapi/npobject_util.h"
47 #include "content/child/plugin_messages.h"
48 #include "content/child/resource_dispatcher.h"
49 #include "content/child/runtime_features.h"
50 #include "content/child/thread_safe_sender.h"
51 #include "content/child/web_database_observer_impl.h"
52 #include "content/child/worker_task_runner.h"
53 #include "content/common/child_process_messages.h"
54 #include "content/common/content_constants_internal.h"
55 #include "content/common/database_messages.h"
56 #include "content/common/dom_storage/dom_storage_messages.h"
57 #include "content/common/frame_messages.h"
58 #include "content/common/gpu/client/context_provider_command_buffer.h"
59 #include "content/common/gpu/client/gpu_channel_host.h"
60 #include "content/common/gpu/gpu_messages.h"
61 #include "content/common/gpu/gpu_process_launch_causes.h"
62 #include "content/common/render_frame_setup.mojom.h"
63 #include "content/common/resource_messages.h"
64 #include "content/common/view_messages.h"
65 #include "content/common/worker_messages.h"
66 #include "content/public/common/content_constants.h"
67 #include "content/public/common/content_paths.h"
68 #include "content/public/common/content_switches.h"
69 #include "content/public/common/renderer_preferences.h"
70 #include "content/public/common/url_constants.h"
71 #include "content/public/renderer/content_renderer_client.h"
72 #include "content/public/renderer/render_process_observer.h"
73 #include "content/public/renderer/render_view_visitor.h"
74 #include "content/renderer/devtools/devtools_agent_filter.h"
75 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
76 #include "content/renderer/dom_storage/webstoragearea_impl.h"
77 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
78 #include "content/renderer/gpu/compositor_output_surface.h"
79 #include "content/renderer/input/input_event_filter.h"
80 #include "content/renderer/input/input_handler_manager.h"
81 #include "content/renderer/media/aec_dump_message_filter.h"
82 #include "content/renderer/media/audio_input_message_filter.h"
83 #include "content/renderer/media/audio_message_filter.h"
84 #include "content/renderer/media/audio_renderer_mixer_manager.h"
85 #include "content/renderer/media/media_stream_center.h"
86 #include "content/renderer/media/midi_message_filter.h"
87 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
88 #include "content/renderer/media/video_capture_impl_manager.h"
89 #include "content/renderer/media/video_capture_message_filter.h"
90 #include "content/renderer/net_info_helper.h"
91 #include "content/renderer/p2p/socket_dispatcher.h"
92 #include "content/renderer/render_frame_proxy.h"
93 #include "content/renderer/render_process_impl.h"
94 #include "content/renderer/render_view_impl.h"
95 #include "content/renderer/renderer_blink_platform_impl.h"
96 #include "content/renderer/scheduler/renderer_scheduler.h"
97 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
98 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
99 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
100 #include "ipc/ipc_channel_handle.h"
101 #include "ipc/ipc_forwarding_message_filter.h"
102 #include "ipc/ipc_platform_file.h"
103 #include "ipc/mojo/ipc_channel_mojo.h"
104 #include "media/base/audio_hardware_config.h"
105 #include "media/base/media.h"
106 #include "media/filters/gpu_video_accelerator_factories.h"
107 #include "mojo/common/common_type_converters.h"
108 #include "net/base/net_errors.h"
109 #include "net/base/net_util.h"
110 #include "skia/ext/event_tracer_impl.h"
111 #include "third_party/WebKit/public/platform/WebString.h"
112 #include "third_party/WebKit/public/platform/WebThread.h"
113 #include "third_party/WebKit/public/web/WebColorName.h"
114 #include "third_party/WebKit/public/web/WebDatabase.h"
115 #include "third_party/WebKit/public/web/WebDocument.h"
116 #include "third_party/WebKit/public/web/WebFrame.h"
117 #include "third_party/WebKit/public/web/WebImageCache.h"
118 #include "third_party/WebKit/public/web/WebKit.h"
119 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
120 #include "third_party/WebKit/public/web/WebPopupMenu.h"
121 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
122 #include "third_party/WebKit/public/web/WebScriptController.h"
123 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
124 #include "third_party/WebKit/public/web/WebView.h"
125 #include "third_party/skia/include/core/SkGraphics.h"
126 #include "ui/base/layout.h"
127 #include "ui/base/ui_base_switches.h"
128 #include "v8/include/v8.h"
130 #if defined(OS_ANDROID)
131 #include <cpu-features.h>
132 #include "content/renderer/android/synchronous_compositor_factory.h"
133 #include "content/renderer/media/android/renderer_demuxer_android.h"
136 #if defined(OS_MACOSX)
137 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
140 #if defined(OS_POSIX)
141 #include "ipc/ipc_channel_posix.h"
149 #include "content/child/npapi/np_channel_base.h"
152 #if defined(ENABLE_PLUGINS)
153 #include "content/renderer/npapi/plugin_channel_host.h"
156 #if defined(ENABLE_WEBRTC)
157 #include "content/renderer/media/peer_connection_tracker.h"
158 #include "content/renderer/media/rtc_peer_connection_handler.h"
159 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
160 #include "content/renderer/media/webrtc_identity_service.h"
163 using base::ThreadRestrictions;
164 using blink::WebDocument;
165 using blink::WebFrame;
166 using blink::WebNetworkStateNotifier;
167 using blink::WebRuntimeFeatures;
168 using blink::WebScriptController;
169 using blink::WebSecurityPolicy;
170 using blink::WebString;
171 using blink::WebView;
177 const int64 kInitialIdleHandlerDelayMs = 1000;
178 const int64 kLongIdleHandlerDelayMs = 30*1000;
180 // Maximum allocation size allowed for image scaling filters that
181 // require pre-scaling. Skia will fallback to a filter that doesn't
182 // require pre-scaling if the default filter would require an
183 // allocation that exceeds this limit.
184 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
186 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden =
189 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
190 // incorrectly from the wrong thread.
191 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
192 lazy_tls = LAZY_INSTANCE_INITIALIZER;
194 class RenderViewZoomer : public RenderViewVisitor {
196 RenderViewZoomer(const std::string& scheme,
197 const std::string& host,
198 double zoom_level) : scheme_(scheme),
200 zoom_level_(zoom_level) {
203 bool Visit(RenderView* render_view) override {
204 WebView* webview = render_view->GetWebView();
205 WebDocument document = webview->mainFrame()->document();
207 // Don't set zoom level for full-page plugin since they don't use the same
209 if (document.isPluginDocument())
211 GURL url(document.url());
212 // Empty scheme works as wildcard that matches any scheme,
213 if ((net::GetHostOrSpecFromURL(url) == host_) &&
214 (scheme_.empty() || scheme_ == url.scheme()) &&
215 !static_cast<RenderViewImpl*>(render_view)
216 ->uses_temporary_zoom_level()) {
217 webview->hidePopups();
218 webview->setZoomLevel(zoom_level_);
224 const std::string scheme_;
225 const std::string host_;
226 const double zoom_level_;
228 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
231 std::string HostToCustomHistogramSuffix(const std::string& host) {
232 if (host == "mail.google.com")
234 if (host == "docs.google.com" || host == "drive.google.com")
236 if (host == "plus.google.com")
238 return std::string();
241 void* CreateHistogram(
242 const char *name, int min, int max, size_t buckets) {
245 std::string histogram_name;
246 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
247 if (render_thread_impl) { // Can be null in tests.
248 histogram_name = render_thread_impl->
249 histogram_customizer()->ConvertToCustomHistogramName(name);
251 histogram_name = std::string(name);
253 base::HistogramBase* histogram = base::Histogram::FactoryGet(
254 histogram_name, min, max, buckets,
255 base::Histogram::kUmaTargetedHistogramFlag);
259 void AddHistogramSample(void* hist, int sample) {
260 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
261 histogram->Add(sample);
264 scoped_ptr<base::SharedMemory> AllocateSharedMemoryFunction(size_t size) {
265 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size);
268 void EnableBlinkPlatformLogChannels(const std::string& channels) {
269 if (channels.empty())
271 base::StringTokenizer t(channels, ", ");
273 blink::enableLogChannel(t.token().c_str());
276 void NotifyTimezoneChangeOnThisThread() {
277 v8::Isolate* isolate = v8::Isolate::GetCurrent();
280 v8::Date::DateTimeConfigurationChangeNotification(isolate);
283 class RenderFrameSetupImpl : public mojo::InterfaceImpl<RenderFrameSetup> {
285 RenderFrameSetupImpl()
286 : routing_id_highmark_(-1) {
289 void GetServiceProviderForFrame(
290 int32_t frame_routing_id,
291 mojo::InterfaceRequest<mojo::ServiceProvider> request) override {
292 // TODO(morrita): This is for investigating http://crbug.com/415059 and
293 // should be removed once it is fixed.
294 CHECK_LT(routing_id_highmark_, frame_routing_id);
295 routing_id_highmark_ = frame_routing_id;
297 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
298 // We can receive a GetServiceProviderForFrame message for a frame not yet
299 // created due to a race between the message and a ViewMsg_New IPC that
300 // triggers creation of the RenderFrame we want.
302 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
303 frame_routing_id, request.PassMessagePipe());
307 frame->BindServiceRegistry(request.PassMessagePipe());
311 int32_t routing_id_highmark_;
314 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
315 mojo::BindToRequest(new RenderFrameSetupImpl(), &request);
318 bool ShouldUseMojoChannel() {
319 return CommandLine::ForCurrentProcess()->HasSwitch(
320 switches::kEnableRendererMojoChannel) ||
321 IPC::ChannelMojo::ShouldBeUsed();
324 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
325 blink::WebGraphicsContext3D::Attributes attributes;
326 attributes.shareResources = true;
327 attributes.depth = false;
328 attributes.stencil = false;
329 attributes.antialias = false;
330 attributes.noAutomaticFlushes = true;
336 // For measuring memory usage after each task. Behind a command line flag.
337 class MemoryObserver : public base::MessageLoop::TaskObserver {
340 ~MemoryObserver() override {}
342 void WillProcessTask(const base::PendingTask& pending_task) override {}
344 void DidProcessTask(const base::PendingTask& pending_task) override {
345 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
349 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
352 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
353 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
354 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
355 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
358 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
360 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
361 const std::string& host, size_t view_count) {
362 if (CommandLine::ForCurrentProcess()->HasSwitch(
363 switches::kDisableHistogramCustomizer)) {
366 // Check if all RenderViews are displaying a page from the same host. If there
367 // is only one RenderView, the common host is this view's host. If there are
368 // many, check if this one shares the common host of the other
369 // RenderViews. It's ok to not detect some cases where the RenderViews share a
370 // common host. This information is only used for producing custom histograms.
373 else if (host != common_host_)
374 SetCommonHost(std::string());
377 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
378 const char* histogram_name) const {
379 std::string name(histogram_name);
380 if (!common_host_histogram_suffix_.empty() &&
381 custom_histograms_.find(name) != custom_histograms_.end())
382 name += common_host_histogram_suffix_;
386 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
387 const std::string& host) {
388 if (host != common_host_) {
390 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
391 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
395 RenderThreadImpl* RenderThreadImpl::current() {
396 return lazy_tls.Pointer()->Get();
399 // When we run plugins in process, we actually run them on the render thread,
400 // which means that we need to make the render thread pump UI events.
401 RenderThreadImpl::RenderThreadImpl()
402 : ChildThread(Options(ShouldUseMojoChannel())) {
406 RenderThreadImpl::RenderThreadImpl(const std::string& channel_name)
407 : ChildThread(Options(channel_name, ShouldUseMojoChannel())) {
411 void RenderThreadImpl::Init() {
412 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
414 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
415 base::PlatformThread::CurrentId(),
416 kTraceEventRendererMainThreadSortIndex);
418 #if defined(OS_MACOSX) || defined(OS_ANDROID)
419 // On Mac and Android, the select popups are rendered by the browser.
420 blink::WebView::setUseExternalPopupMenus(true);
423 lazy_tls.Pointer()->Set(this);
425 // Register this object as the main thread.
426 ChildProcess::current()->set_main_thread(this);
428 // In single process the single process is all there is.
429 suspend_webkit_shared_timer_ = true;
430 notify_webkit_of_modal_loop_ = true;
431 webkit_shared_timer_suspended_ = false;
433 hidden_widget_count_ = 0;
434 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
435 idle_notifications_to_skip_ = 0;
436 layout_test_mode_ = false;
438 appcache_dispatcher_.reset(
439 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
440 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
441 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
442 thread_safe_sender()));
443 renderer_scheduler_ = RendererScheduler::Create();
444 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
446 media_stream_center_ = NULL;
448 db_message_filter_ = new DBMessageFilter();
449 AddFilter(db_message_filter_.get());
451 vc_manager_.reset(new VideoCaptureImplManager());
452 AddFilter(vc_manager_->video_capture_message_filter());
454 #if defined(ENABLE_WEBRTC)
455 peer_connection_tracker_.reset(new PeerConnectionTracker());
456 AddObserver(peer_connection_tracker_.get());
458 p2p_socket_dispatcher_ =
459 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
460 AddFilter(p2p_socket_dispatcher_.get());
462 webrtc_identity_service_.reset(new WebRTCIdentityService());
464 aec_dump_message_filter_ =
465 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
466 message_loop()->message_loop_proxy());
467 AddFilter(aec_dump_message_filter_.get());
469 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
470 p2p_socket_dispatcher_.get()));
471 #endif // defined(ENABLE_WEBRTC)
473 audio_input_message_filter_ =
474 new AudioInputMessageFilter(GetIOMessageLoopProxy());
475 AddFilter(audio_input_message_filter_.get());
477 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
478 AddFilter(audio_message_filter_.get());
480 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
481 AddFilter(midi_message_filter_.get());
483 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
485 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
487 GetContentClient()->renderer()->RenderThreadStarted();
489 InitSkiaEventTracer();
491 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
493 is_impl_side_painting_enabled_ =
494 command_line.HasSwitch(switches::kEnableImplSidePainting);
495 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
496 is_impl_side_painting_enabled_);
498 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
500 #if defined(OS_MACOSX) || defined(OS_ANDROID)
501 is_one_copy_enabled_ = command_line.HasSwitch(switches::kEnableOneCopy);
503 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
506 if (command_line.HasSwitch(switches::kDisableLCDText)) {
507 is_lcd_text_enabled_ = false;
508 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
509 is_lcd_text_enabled_ = true;
511 #if defined(OS_ANDROID)
512 is_lcd_text_enabled_ = false;
514 is_lcd_text_enabled_ = true;
518 is_gpu_rasterization_enabled_ =
519 command_line.HasSwitch(switches::kEnableGpuRasterization);
520 is_gpu_rasterization_forced_ =
521 command_line.HasSwitch(switches::kForceGpuRasterization);
523 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
524 is_distance_field_text_enabled_ = false;
525 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
526 is_distance_field_text_enabled_ = true;
528 is_distance_field_text_enabled_ = false;
531 // Note that under Linux, the media library will normally already have
532 // been initialized by the Zygote before this instance became a Renderer.
533 base::FilePath media_path;
534 PathService::Get(DIR_MEDIA_LIBS, &media_path);
535 if (!media_path.empty())
536 media::InitializeMediaLibrary(media_path);
538 memory_pressure_listener_.reset(new base::MemoryPressureListener(
539 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
541 std::vector<base::DiscardableMemoryType> supported_types;
542 base::DiscardableMemory::GetSupportedTypes(&supported_types);
543 DCHECK(!supported_types.empty());
545 // The default preferred type is always the first one in list.
546 base::DiscardableMemoryType type = supported_types[0];
548 if (command_line.HasSwitch(switches::kUseDiscardableMemory)) {
549 std::string requested_type_name = command_line.GetSwitchValueASCII(
550 switches::kUseDiscardableMemory);
551 base::DiscardableMemoryType requested_type =
552 base::DiscardableMemory::GetNamedType(requested_type_name);
553 if (std::find(supported_types.begin(),
554 supported_types.end(),
555 requested_type) != supported_types.end()) {
556 type = requested_type;
558 LOG(ERROR) << "Requested discardable memory type is not supported.";
562 base::DiscardableMemory::SetPreferredType(type);
564 if (is_impl_side_painting_enabled_) {
565 int num_raster_threads = 0;
566 std::string string_value =
567 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
568 bool parsed_num_raster_threads =
569 base::StringToInt(string_value, &num_raster_threads);
570 DCHECK(parsed_num_raster_threads) << string_value;
571 DCHECK_GT(num_raster_threads, 0);
572 cc::RasterWorkerPool::SetNumRasterThreads(num_raster_threads);
575 base::DiscardableMemoryShmemAllocator::SetInstance(
576 ChildThread::discardable_shared_memory_manager());
578 service_registry()->AddService<RenderFrameSetup>(
579 base::Bind(CreateRenderFrameSetup));
581 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
584 RenderThreadImpl::~RenderThreadImpl() {
585 for (std::map<int, mojo::MessagePipeHandle>::iterator it =
586 pending_render_frame_connects_.begin();
587 it != pending_render_frame_connects_.end();
589 mojo::CloseRaw(it->second);
593 void RenderThreadImpl::Shutdown() {
595 RenderProcessObserver, observers_, OnRenderProcessShutdown());
597 ChildThread::Shutdown();
599 if (memory_observer_) {
600 message_loop()->RemoveTaskObserver(memory_observer_.get());
601 memory_observer_.reset();
604 // Wait for all databases to be closed.
605 if (blink_platform_impl_) {
606 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
607 // processing timer events while we're already in the process of shutting
608 // down blink, put a ScopePageLoadDeferrer on the stack.
609 WebView::willEnterModalLoop();
610 blink_platform_impl_->web_database_observer_impl()
611 ->WaitForAllDatabasesToClose();
612 WebView::didExitModalLoop();
615 // Shutdown in reverse of the initialization order.
616 if (devtools_agent_message_filter_.get()) {
617 RemoveFilter(devtools_agent_message_filter_.get());
618 devtools_agent_message_filter_ = NULL;
621 RemoveFilter(audio_input_message_filter_.get());
622 audio_input_message_filter_ = NULL;
624 #if defined(ENABLE_WEBRTC)
625 RTCPeerConnectionHandler::DestructAllHandlers();
627 peer_connection_factory_.reset();
629 RemoveFilter(vc_manager_->video_capture_message_filter());
632 RemoveFilter(db_message_filter_.get());
633 db_message_filter_ = NULL;
635 // Shutdown the file thread if it's running.
637 file_thread_->Stop();
639 if (compositor_output_surface_filter_.get()) {
640 RemoveFilter(compositor_output_surface_filter_.get());
641 compositor_output_surface_filter_ = NULL;
644 media_thread_.reset();
646 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
647 RemoveFilter(audio_message_filter_.get());
648 audio_message_filter_ = NULL;
650 compositor_thread_.reset();
651 input_handler_manager_.reset();
652 if (input_event_filter_.get()) {
653 RemoveFilter(input_event_filter_.get());
654 input_event_filter_ = NULL;
657 // RemoveEmbeddedWorkerRoute may be called while deleting
658 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
660 embedded_worker_dispatcher_.reset();
662 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
663 // hold pointers to V8 objects (e.g., via pending requests).
664 main_thread_indexed_db_dispatcher_.reset();
666 main_thread_compositor_task_runner_ = NULL;
668 if (blink_platform_impl_)
671 lazy_tls.Pointer()->Set(NULL);
675 // Clean up plugin channels before this thread goes away.
676 NPChannelBase::CleanupChannels();
680 bool RenderThreadImpl::Send(IPC::Message* msg) {
681 // Certain synchronous messages cannot always be processed synchronously by
682 // the browser, e.g., putting up UI and waiting for the user. This could cause
683 // a complete hang of Chrome if a windowed plug-in is trying to communicate
684 // with the renderer thread since the browser's UI thread could be stuck
685 // (within a Windows API call) trying to synchronously communicate with the
686 // plug-in. The remedy is to pump messages on this thread while the browser
687 // is processing this request. This creates an opportunity for re-entrancy
688 // into WebKit, so we need to take care to disable callbacks, timers, and
689 // pending network loads that could trigger such callbacks.
690 bool pumping_events = false;
691 if (msg->is_sync()) {
692 if (msg->is_caller_pumping_messages()) {
693 pumping_events = true;
697 bool suspend_webkit_shared_timer = true; // default value
698 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
700 bool notify_webkit_of_modal_loop = true; // default value
701 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
703 #if defined(ENABLE_PLUGINS)
704 int render_view_id = MSG_ROUTING_NONE;
707 if (pumping_events) {
708 if (suspend_webkit_shared_timer)
709 blink_platform_impl_->SuspendSharedTimer();
711 if (notify_webkit_of_modal_loop)
712 WebView::willEnterModalLoop();
713 #if defined(ENABLE_PLUGINS)
714 RenderViewImpl* render_view =
715 RenderViewImpl::FromRoutingID(msg->routing_id());
717 render_view_id = msg->routing_id();
718 PluginChannelHost::Broadcast(
719 new PluginMsg_SignalModalDialogEvent(render_view_id));
724 bool rv = ChildThread::Send(msg);
726 if (pumping_events) {
727 #if defined(ENABLE_PLUGINS)
728 if (render_view_id != MSG_ROUTING_NONE) {
729 PluginChannelHost::Broadcast(
730 new PluginMsg_ResetModalDialogEvent(render_view_id));
734 if (notify_webkit_of_modal_loop)
735 WebView::didExitModalLoop();
737 if (suspend_webkit_shared_timer)
738 blink_platform_impl_->ResumeSharedTimer();
744 base::MessageLoop* RenderThreadImpl::GetMessageLoop() {
745 return message_loop();
748 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
752 std::string RenderThreadImpl::GetLocale() {
753 // The browser process should have passed the locale to the renderer via the
754 // --lang command line flag.
755 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
756 const std::string& lang =
757 parsed_command_line.GetSwitchValueASCII(switches::kLang);
758 DCHECK(!lang.empty());
762 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
763 return sync_message_filter();
766 scoped_refptr<base::MessageLoopProxy>
767 RenderThreadImpl::GetIOMessageLoopProxy() {
768 return ChildProcess::current()->io_message_loop_proxy();
771 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
772 ChildThread::GetRouter()->AddRoute(routing_id, listener);
773 std::map<int, mojo::MessagePipeHandle>::iterator it =
774 pending_render_frame_connects_.find(routing_id);
775 if (it == pending_render_frame_connects_.end())
778 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
782 mojo::ScopedMessagePipeHandle handle(it->second);
783 pending_render_frame_connects_.erase(it);
784 frame->BindServiceRegistry(handle.Pass());
787 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
788 ChildThread::GetRouter()->RemoveRoute(routing_id);
791 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
792 IPC::Listener* listener) {
793 AddRoute(routing_id, listener);
794 if (devtools_agent_message_filter_.get()) {
795 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
800 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
801 RemoveRoute(routing_id);
802 if (devtools_agent_message_filter_.get()) {
803 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
808 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
810 mojo::ScopedMessagePipeHandle handle) {
811 std::pair<std::map<int, mojo::MessagePipeHandle>::iterator, bool> result =
812 pending_render_frame_connects_.insert(
813 std::make_pair(routing_id, handle.release()));
814 CHECK(result.second) << "Inserting a duplicate item.";
817 int RenderThreadImpl::GenerateRoutingID() {
818 int routing_id = MSG_ROUTING_NONE;
819 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
823 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
824 channel()->AddFilter(filter);
827 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
828 channel()->RemoveFilter(filter);
831 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
832 observers_.AddObserver(observer);
835 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
836 observers_.RemoveObserver(observer);
839 void RenderThreadImpl::SetResourceDispatcherDelegate(
840 ResourceDispatcherDelegate* delegate) {
841 resource_dispatcher()->set_delegate(delegate);
844 void RenderThreadImpl::EnsureWebKitInitialized() {
845 if (blink_platform_impl_)
848 blink_platform_impl_.reset(
849 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
850 blink::initialize(blink_platform_impl_.get());
852 v8::Isolate* isolate = blink::mainThreadIsolate();
854 isolate->SetCounterFunction(base::StatsTable::FindLocation);
855 isolate->SetCreateHistogramFunction(CreateHistogram);
856 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
858 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
860 main_thread_compositor_task_runner_ =
861 renderer_scheduler()->CompositorTaskRunner();
863 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
865 #if defined(OS_ANDROID)
866 if (SynchronousCompositorFactory* factory =
867 SynchronousCompositorFactory::GetInstance())
868 compositor_message_loop_proxy_ =
869 factory->GetCompositorMessageLoop();
871 if (!compositor_message_loop_proxy_.get()) {
872 compositor_thread_.reset(new base::Thread("Compositor"));
873 compositor_thread_->Start();
874 #if defined(OS_ANDROID)
875 compositor_thread_->SetPriority(base::kThreadPriority_Display);
877 compositor_message_loop_proxy_ =
878 compositor_thread_->message_loop_proxy();
879 compositor_message_loop_proxy_->PostTask(
881 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
885 InputHandlerManagerClient* input_handler_manager_client = NULL;
886 #if defined(OS_ANDROID)
887 if (SynchronousCompositorFactory* factory =
888 SynchronousCompositorFactory::GetInstance()) {
889 input_handler_manager_client = factory->GetInputHandlerManagerClient();
892 if (!input_handler_manager_client) {
893 input_event_filter_ =
894 new InputEventFilter(this,
895 main_thread_compositor_task_runner_,
896 compositor_message_loop_proxy_);
897 AddFilter(input_event_filter_.get());
898 input_handler_manager_client = input_event_filter_.get();
900 input_handler_manager_.reset(
901 new InputHandlerManager(compositor_message_loop_proxy_,
902 input_handler_manager_client));
905 scoped_refptr<base::MessageLoopProxy> output_surface_loop;
907 output_surface_loop = compositor_message_loop_proxy_;
909 output_surface_loop = base::MessageLoopProxy::current();
911 compositor_output_surface_filter_ =
912 CompositorOutputSurface::CreateFilter(output_surface_loop.get());
913 AddFilter(compositor_output_surface_filter_.get());
915 RenderThreadImpl::RegisterSchemes();
917 EnableBlinkPlatformLogChannels(
918 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
920 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
922 if (!media::IsMediaLibraryInitialized()) {
923 WebRuntimeFeatures::enableWebAudio(false);
926 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
928 devtools_agent_message_filter_ = new DevToolsAgentFilter();
929 AddFilter(devtools_agent_message_filter_.get());
931 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
932 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
934 cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction);
936 // Limit use of the scaled image cache to when deferred image decoding is
938 if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
939 !is_impl_side_painting_enabled_)
940 SkGraphics::SetResourceCacheTotalByteLimit(0u);
942 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
943 kImageCacheSingleAllocationByteLimit);
945 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
946 memory_observer_.reset(new MemoryObserver());
947 message_loop()->AddTaskObserver(memory_observer_.get());
951 void RenderThreadImpl::RegisterSchemes() {
952 // swappedout: pages should not be accessible, and should also
953 // be treated as empty documents that can commit synchronously.
954 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
955 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
956 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
959 void RenderThreadImpl::NotifyTimezoneChange() {
960 NotifyTimezoneChangeOnThisThread();
961 RenderThread::Get()->PostTaskToAllWebWorkers(
962 base::Bind(&NotifyTimezoneChangeOnThisThread));
965 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
966 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
969 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
970 Send(new ViewHostMsg_UserMetricsRecordAction(action));
973 scoped_ptr<base::SharedMemory>
974 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
975 if (size > static_cast<size_t>(std::numeric_limits<int>::max()))
976 return scoped_ptr<base::SharedMemory>();
978 base::SharedMemoryHandle handle;
980 IPC::Message* message =
981 new ChildProcessHostMsg_SyncAllocateSharedMemory(size, &handle);
983 // Allow calling this from the compositor thread.
984 if (base::MessageLoop::current() == message_loop())
985 success = ChildThread::Send(message);
987 success = sync_message_filter()->Send(message);
990 return scoped_ptr<base::SharedMemory>();
992 if (!base::SharedMemory::IsHandleValid(handle))
993 return scoped_ptr<base::SharedMemory>();
995 return scoped_ptr<base::SharedMemory>(new base::SharedMemory(handle, false));
998 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
999 WebScriptController::registerExtension(extension);
1002 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1003 idle_notification_delay_in_ms_ = initial_delay_ms;
1005 idle_timer_.Start(FROM_HERE,
1006 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1007 this, &RenderThreadImpl::IdleHandler);
1010 void RenderThreadImpl::IdleHandler() {
1011 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1012 GetContentClient()->renderer()->
1013 RunIdleHandlerWhenWidgetsHidden();
1014 if (run_in_foreground_tab) {
1015 if (idle_notifications_to_skip_ > 0) {
1016 --idle_notifications_to_skip_;
1018 base::allocator::ReleaseFreeMemory();
1019 base::DiscardableMemory::ReduceMemoryUsage();
1021 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1025 base::allocator::ReleaseFreeMemory();
1026 base::DiscardableMemory::ReleaseFreeMemory();
1028 // Continue the idle timer if the webkit shared timer is not suspended or
1029 // something is left to do.
1030 bool continue_timer = !webkit_shared_timer_suspended_;
1032 if (blink::mainThreadIsolate() &&
1033 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1034 continue_timer = true;
1036 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1037 continue_timer = true;
1040 // Schedule next invocation. When the tab is originally hidden, an invocation
1041 // is scheduled for kInitialIdleHandlerDelayMs in
1042 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1043 // After that, idle calls can be much less frequent, so run at a maximum of
1044 // once every kLongIdleHandlerDelayMs.
1045 // Dampen the delay using the algorithm (if delay is in seconds):
1046 // delay = delay + 1 / (delay + 2)
1047 // Using floor(delay) has a dampening effect such as:
1048 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1049 // If the delay is in milliseconds, the above formula is equivalent to:
1050 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1051 // which is equivalent to
1052 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1053 if (continue_timer) {
1054 ScheduleIdleHandler(
1055 std::max(kLongIdleHandlerDelayMs,
1056 idle_notification_delay_in_ms_ +
1057 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1063 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1066 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1067 return idle_notification_delay_in_ms_;
1070 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1071 int64 idle_notification_delay_in_ms) {
1072 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1075 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1076 child_histogram_message_filter()->SendHistograms(sequence_number);
1079 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1080 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1083 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1084 bool result = false;
1085 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1089 void RenderThreadImpl::PostponeIdleNotification() {
1090 idle_notifications_to_skip_ = 2;
1093 scoped_refptr<media::GpuVideoAcceleratorFactories>
1094 RenderThreadImpl::GetGpuFactories() {
1095 DCHECK(IsMainThread());
1097 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1098 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
1099 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1100 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1101 GetMediaThreadTaskRunner();
1102 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1103 if (!gpu_va_context_provider_.get() ||
1104 gpu_va_context_provider_->DestroyedOnMainThread()) {
1105 if (!gpu_channel_host.get()) {
1106 gpu_channel_host = EstablishGpuChannelSync(
1107 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1109 blink::WebGraphicsContext3D::Attributes attributes;
1110 bool lose_context_when_out_of_memory = false;
1111 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1113 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1114 gpu_channel_host.get(),
1116 lose_context_when_out_of_memory,
1117 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1118 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1120 "GPU-VideoAccelerator-Offscreen");
1123 if (gpu_va_context_provider_.get()) {
1124 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1125 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_);
1127 return gpu_factories;
1130 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1131 RenderThreadImpl::CreateOffscreenContext3d() {
1132 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1133 bool lose_context_when_out_of_memory = true;
1135 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1136 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1137 return make_scoped_ptr(
1138 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1139 gpu_channel_host.get(),
1141 lose_context_when_out_of_memory,
1142 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1143 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1147 scoped_refptr<webkit::gpu::ContextProviderWebContext>
1148 RenderThreadImpl::SharedMainThreadContextProvider() {
1149 DCHECK(IsMainThread());
1150 if (!shared_main_thread_contexts_.get() ||
1151 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1152 shared_main_thread_contexts_ = NULL;
1153 #if defined(OS_ANDROID)
1154 if (SynchronousCompositorFactory* factory =
1155 SynchronousCompositorFactory::GetInstance()) {
1156 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1157 GetOffscreenAttribs(), "Offscreen-MainThread");
1160 if (!shared_main_thread_contexts_.get()) {
1161 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1162 CreateOffscreenContext3d(), "Offscreen-MainThread");
1164 if (shared_main_thread_contexts_.get() &&
1165 !shared_main_thread_contexts_->BindToCurrentThread())
1166 shared_main_thread_contexts_ = NULL;
1168 return shared_main_thread_contexts_;
1171 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1172 if (!audio_renderer_mixer_manager_) {
1173 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1174 GetAudioHardwareConfig()));
1177 return audio_renderer_mixer_manager_.get();
1180 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1181 if (!audio_hardware_config_) {
1182 media::AudioParameters input_params;
1183 media::AudioParameters output_params;
1184 Send(new ViewHostMsg_GetAudioHardwareConfig(
1185 &input_params, &output_params));
1187 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1188 input_params, output_params));
1189 audio_message_filter_->SetAudioHardwareConfig(audio_hardware_config_.get());
1192 return audio_hardware_config_.get();
1195 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1196 return ChildProcess::current()->GetShutDownEvent();
1200 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1201 const base::string16& str) {
1202 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1205 void RenderThreadImpl::PreCacheFont(const LOGFONT& log_font) {
1206 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
1209 void RenderThreadImpl::ReleaseCachedFonts() {
1210 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1215 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1216 return service_registry();
1219 bool RenderThreadImpl::IsMainThread() {
1223 base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1224 return message_loop();
1227 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1228 return io_message_loop_proxy_;
1231 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1233 return scoped_ptr<base::SharedMemory>(
1234 HostAllocateSharedMemoryBuffer(size));
1237 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1239 const GPUCreateCommandBufferConfig& init_params,
1242 "RenderThreadImpl::CreateViewCommandBuffer",
1246 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1247 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1253 // Allow calling this from the compositor thread.
1254 thread_safe_sender()->Send(message);
1259 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1260 suspend_webkit_shared_timer_ = false;
1263 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1264 notify_webkit_of_modal_loop_ = false;
1267 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1268 ObserverListBase<RenderProcessObserver>::Iterator it(observers_);
1269 RenderProcessObserver* observer;
1270 while ((observer = it.GetNext()) != NULL) {
1271 if (observer->OnControlMessageReceived(msg))
1275 // Some messages are handled by delegates.
1276 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1277 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1278 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1282 bool handled = true;
1283 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1284 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1285 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1286 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1287 OnSetZoomLevelForCurrentURL)
1288 // TODO(port): removed from render_messages_internal.h;
1289 // is there a new non-windows message I should add here?
1290 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1291 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1292 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1293 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1294 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1295 #if defined(OS_ANDROID)
1296 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1297 OnSetWebKitSharedTimersSuspended)
1299 #if defined(OS_MACOSX)
1300 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1302 #if defined(ENABLE_PLUGINS)
1303 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1305 IPC_MESSAGE_UNHANDLED(handled = false)
1306 IPC_END_MESSAGE_MAP()
1310 void RenderThreadImpl::OnCreateNewFrame(int routing_id,
1311 int parent_routing_id,
1312 int proxy_routing_id) {
1313 RenderFrameImpl::CreateFrame(routing_id, parent_routing_id, proxy_routing_id);
1316 void RenderThreadImpl::OnCreateNewFrameProxy(int routing_id,
1317 int parent_routing_id,
1318 int render_view_routing_id) {
1319 RenderFrameProxy::CreateFrameProxy(
1320 routing_id, parent_routing_id, render_view_routing_id);
1323 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1324 const std::string& host,
1325 double zoom_level) {
1326 RenderViewZoomer zoomer(scheme, host, zoom_level);
1327 RenderView::ForEach(&zoomer);
1330 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1331 EnsureWebKitInitialized();
1332 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1333 RenderViewImpl::Create(params.opener_route_id,
1334 params.window_was_created_with_opener,
1335 params.renderer_preferences,
1336 params.web_preferences,
1338 params.main_frame_routing_id,
1340 params.session_storage_namespace_id,
1344 params.proxy_routing_id,
1346 params.never_visible,
1347 params.next_page_id,
1348 params.screen_info);
1351 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1352 CauseForGpuLaunch cause_for_gpu_launch) {
1353 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1355 if (gpu_channel_.get()) {
1356 // Do nothing if we already have a GPU channel or are already
1357 // establishing one.
1358 if (!gpu_channel_->IsLost())
1359 return gpu_channel_.get();
1361 // Recreate the channel if it has been lost.
1362 gpu_channel_ = NULL;
1365 // Ask the browser for the channel name.
1367 IPC::ChannelHandle channel_handle;
1368 gpu::GPUInfo gpu_info;
1369 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1373 #if defined(OS_POSIX)
1374 channel_handle.socket.fd == -1 ||
1376 channel_handle.name.empty()) {
1377 // Otherwise cancel the connection.
1381 GetContentClient()->SetGpuInfo(gpu_info);
1383 // Cache some variables that are needed on the compositor thread for our
1384 // implementation of GpuChannelHostFactory.
1385 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1388 GpuChannelHost::Create(this,
1391 ChildProcess::current()->GetShutDownEvent(),
1392 gpu_memory_buffer_manager());
1393 return gpu_channel_.get();
1396 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1397 blink::WebMediaStreamCenterClient* client) {
1398 #if defined(OS_ANDROID)
1399 if (CommandLine::ForCurrentProcess()->HasSwitch(
1400 switches::kDisableWebRTC))
1404 #if defined(ENABLE_WEBRTC)
1405 if (!media_stream_center_) {
1406 media_stream_center_ = GetContentClient()->renderer()
1407 ->OverrideCreateWebMediaStreamCenter(client);
1408 if (!media_stream_center_) {
1409 scoped_ptr<MediaStreamCenter> media_stream_center(
1410 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1411 media_stream_center_ = media_stream_center.release();
1415 return media_stream_center_;
1418 #if defined(ENABLE_WEBRTC)
1419 PeerConnectionDependencyFactory*
1420 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1421 return peer_connection_factory_.get();
1425 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1426 if (!gpu_channel_.get())
1429 if (gpu_channel_->IsLost())
1432 return gpu_channel_.get();
1435 #if defined(ENABLE_PLUGINS)
1436 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1437 EnsureWebKitInitialized();
1438 // The call below will cause a GetPlugins call with refresh=true, but at this
1439 // point we already know that the browser has refreshed its list, so disable
1440 // refresh temporarily to prevent each renderer process causing the list to be
1442 blink_platform_impl_->set_plugin_refresh_allowed(false);
1443 blink::resetPluginCache(reload_pages);
1444 blink_platform_impl_->set_plugin_refresh_allowed(true);
1446 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1450 void RenderThreadImpl::OnNetworkTypeChanged(
1451 net::NetworkChangeNotifier::ConnectionType type) {
1452 EnsureWebKitInitialized();
1453 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1454 WebNetworkStateNotifier::setOnLine(online);
1456 RenderProcessObserver, observers_, NetworkStateChanged(online));
1457 WebNetworkStateNotifier::setWebConnectionType(
1458 NetConnectionTypeToWebConnectionType(type));
1461 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1462 GetContentClient()->SetActiveURL(data);
1466 void RenderThreadImpl::OnUpdateTimezone() {
1467 if (!blink_platform_impl_)
1469 NotifyTimezoneChange();
1472 #if defined(OS_ANDROID)
1473 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1474 if (suspend_webkit_shared_timer_) {
1475 EnsureWebKitInitialized();
1477 blink_platform_impl_->SuspendSharedTimer();
1479 blink_platform_impl_->ResumeSharedTimer();
1481 webkit_shared_timer_suspended_ = suspend;
1486 #if defined(OS_MACOSX)
1487 void RenderThreadImpl::OnUpdateScrollbarTheme(
1488 float initial_button_delay,
1489 float autoscroll_button_delay,
1490 bool jump_on_track_click,
1491 blink::ScrollerStyle preferred_scroller_style,
1493 EnsureWebKitInitialized();
1494 static_cast<WebScrollbarBehaviorImpl*>(
1495 blink_platform_impl_->scrollbarBehavior())
1496 ->set_jump_on_track_click(jump_on_track_click);
1497 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1498 autoscroll_button_delay,
1499 preferred_scroller_style,
1504 void RenderThreadImpl::OnCreateNewSharedWorker(
1505 const WorkerProcessMsg_CreateWorker_Params& params) {
1506 // EmbeddedSharedWorkerStub will self-destruct.
1507 new EmbeddedSharedWorkerStub(params.url,
1509 params.content_security_policy,
1510 params.security_policy_type,
1511 params.pause_on_start,
1515 void RenderThreadImpl::OnMemoryPressure(
1516 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1517 base::allocator::ReleaseFreeMemory();
1519 // Trigger full v8 garbage collection on critical memory notification. This
1520 // will potentially hang the renderer for a long time, however, when we
1521 // receive a memory pressure notification, we might be about to be killed.
1522 if (blink_platform_impl_ && blink::mainThreadIsolate()) {
1523 blink::mainThreadIsolate()->LowMemoryNotification();
1526 if (memory_pressure_level ==
1527 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1528 if (blink_platform_impl_) {
1529 // Clear the image cache. Do not call into blink if it is not initialized.
1530 blink::WebImageCache::clear();
1533 // Purge Skia font cache, by setting it to 0 and then again to the previous
1535 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1536 SkGraphics::SetFontCacheLimit(font_cache_limit);
1540 scoped_refptr<base::MessageLoopProxy>
1541 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1542 DCHECK(message_loop() == base::MessageLoop::current());
1543 if (!file_thread_) {
1544 file_thread_.reset(new base::Thread("Renderer::FILE"));
1545 file_thread_->Start();
1547 return file_thread_->message_loop_proxy();
1550 scoped_refptr<base::SingleThreadTaskRunner>
1551 RenderThreadImpl::GetMediaThreadTaskRunner() {
1552 DCHECK(message_loop() == base::MessageLoop::current());
1553 if (!media_thread_) {
1554 media_thread_.reset(new base::Thread("Media"));
1555 media_thread_->Start();
1557 #if defined(OS_ANDROID)
1558 renderer_demuxer_ = new RendererDemuxerAndroid();
1559 AddFilter(renderer_demuxer_.get());
1562 return media_thread_->message_loop_proxy();
1565 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1566 blink_platform_impl_->sampleGamepads(*data);
1569 void RenderThreadImpl::WidgetCreated() {
1573 void RenderThreadImpl::WidgetDestroyed() {
1577 void RenderThreadImpl::WidgetHidden() {
1578 DCHECK_LT(hidden_widget_count_, widget_count_);
1579 hidden_widget_count_++;
1581 if (widget_count_ && hidden_widget_count_ == widget_count_) {
1582 // TODO(reveman): Remove this when we have a better mechanism to prevent
1583 // total discardable memory used by all renderers from growing too large.
1584 base::internal::DiscardableMemoryEmulated::
1585 ReduceMemoryUsageUntilWithinLimit(
1586 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden);
1588 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1589 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1593 void RenderThreadImpl::WidgetRestored() {
1594 DCHECK_GT(hidden_widget_count_, 0);
1595 hidden_widget_count_--;
1597 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1601 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1604 } // namespace content