Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blob08016d760e1858be4431575e2cf3e711ccbc583c
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/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/shared_memory.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/metrics/stats_table.h"
22 #include "base/path_service.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/utf_string_conversions.h"
27 #include "base/threading/thread_local.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/values.h"
30 #include "cc/base/switches.h"
31 #include "cc/resources/raster_worker_pool.h"
32 #include "content/child/appcache/appcache_dispatcher.h"
33 #include "content/child/appcache/appcache_frontend_impl.h"
34 #include "content/child/child_histogram_message_filter.h"
35 #include "content/child/db_message_filter.h"
36 #include "content/child/indexed_db/indexed_db_dispatcher.h"
37 #include "content/child/indexed_db/indexed_db_message_filter.h"
38 #include "content/child/npapi/npobject_util.h"
39 #include "content/child/plugin_messages.h"
40 #include "content/child/resource_dispatcher.h"
41 #include "content/child/runtime_features.h"
42 #include "content/child/thread_safe_sender.h"
43 #include "content/child/web_database_observer_impl.h"
44 #include "content/child/worker_task_runner.h"
45 #include "content/common/child_process_messages.h"
46 #include "content/common/content_constants_internal.h"
47 #include "content/common/database_messages.h"
48 #include "content/common/dom_storage/dom_storage_messages.h"
49 #include "content/common/gpu/client/context_provider_command_buffer.h"
50 #include "content/common/gpu/client/gpu_channel_host.h"
51 #include "content/common/gpu/client/gpu_memory_buffer_impl.h"
52 #include "content/common/gpu/gpu_messages.h"
53 #include "content/common/gpu/gpu_process_launch_causes.h"
54 #include "content/common/mojo/mojo_service_names.h"
55 #include "content/common/resource_messages.h"
56 #include "content/common/view_messages.h"
57 #include "content/common/worker_messages.h"
58 #include "content/public/common/content_constants.h"
59 #include "content/public/common/content_paths.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/renderer_preferences.h"
62 #include "content/public/common/url_constants.h"
63 #include "content/public/renderer/content_renderer_client.h"
64 #include "content/public/renderer/render_process_observer.h"
65 #include "content/public/renderer/render_view_visitor.h"
66 #include "content/renderer/devtools/devtools_agent_filter.h"
67 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
68 #include "content/renderer/dom_storage/webstoragearea_impl.h"
69 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
70 #include "content/renderer/gamepad_shared_memory_reader.h"
71 #include "content/renderer/gpu/compositor_output_surface.h"
72 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
73 #include "content/renderer/input/input_event_filter.h"
74 #include "content/renderer/input/input_handler_manager.h"
75 #include "content/renderer/media/audio_input_message_filter.h"
76 #include "content/renderer/media/audio_message_filter.h"
77 #include "content/renderer/media/audio_renderer_mixer_manager.h"
78 #include "content/renderer/media/media_stream_center.h"
79 #include "content/renderer/media/media_stream_dependency_factory.h"
80 #include "content/renderer/media/midi_message_filter.h"
81 #include "content/renderer/media/peer_connection_tracker.h"
82 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
83 #include "content/renderer/media/video_capture_impl_manager.h"
84 #include "content/renderer/media/video_capture_message_filter.h"
85 #include "content/renderer/media/webrtc_identity_service.h"
86 #include "content/renderer/p2p/socket_dispatcher.h"
87 #include "content/renderer/render_process_impl.h"
88 #include "content/renderer/render_view_impl.h"
89 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
90 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
91 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
92 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
93 #include "content/renderer/web_ui_setup_impl.h"
94 #include "grit/content_resources.h"
95 #include "ipc/ipc_channel_handle.h"
96 #include "ipc/ipc_forwarding_message_filter.h"
97 #include "ipc/ipc_platform_file.h"
98 #include "media/base/audio_hardware_config.h"
99 #include "media/base/media.h"
100 #include "media/filters/gpu_video_accelerator_factories.h"
101 #include "mojo/common/common_type_converters.h"
102 #include "net/base/net_errors.h"
103 #include "net/base/net_util.h"
104 #include "skia/ext/event_tracer_impl.h"
105 #include "third_party/WebKit/public/platform/WebString.h"
106 #include "third_party/WebKit/public/web/WebColorName.h"
107 #include "third_party/WebKit/public/web/WebDatabase.h"
108 #include "third_party/WebKit/public/web/WebDocument.h"
109 #include "third_party/WebKit/public/web/WebFrame.h"
110 #include "third_party/WebKit/public/web/WebImageCache.h"
111 #include "third_party/WebKit/public/web/WebKit.h"
112 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
113 #include "third_party/WebKit/public/web/WebPopupMenu.h"
114 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
115 #include "third_party/WebKit/public/web/WebScriptController.h"
116 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
117 #include "third_party/WebKit/public/web/WebView.h"
118 #include "third_party/skia/include/core/SkGraphics.h"
119 #include "ui/base/layout.h"
120 #include "ui/base/ui_base_switches.h"
121 #include "v8/include/v8.h"
122 #include "webkit/renderer/compositor_bindings/web_external_bitmap_impl.h"
123 #include "webkit/renderer/compositor_bindings/web_layer_impl.h"
125 #if defined(OS_ANDROID)
126 #include <cpu-features.h>
127 #include "content/renderer/android/synchronous_compositor_factory.h"
128 #include "content/renderer/media/android/renderer_demuxer_android.h"
129 #endif
131 #if defined(OS_MACOSX)
132 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
133 #endif
135 #if defined(OS_POSIX)
136 #include "ipc/ipc_channel_posix.h"
137 #endif
139 #if defined(OS_WIN)
140 #include <windows.h>
141 #include <objbase.h>
142 #else
143 // TODO(port)
144 #include "base/memory/scoped_handle.h"
145 #include "content/child/npapi/np_channel_base.h"
146 #endif
148 #if defined(ENABLE_PLUGINS)
149 #include "content/renderer/npapi/plugin_channel_host.h"
150 #endif
152 using base::ThreadRestrictions;
153 using blink::WebDocument;
154 using blink::WebFrame;
155 using blink::WebNetworkStateNotifier;
156 using blink::WebRuntimeFeatures;
157 using blink::WebScriptController;
158 using blink::WebSecurityPolicy;
159 using blink::WebString;
160 using blink::WebView;
162 namespace content {
164 namespace {
166 const int64 kInitialIdleHandlerDelayMs = 1000;
167 const int64 kShortIdleHandlerDelayMs = 1000;
168 const int64 kLongIdleHandlerDelayMs = 30*1000;
169 const int kIdleCPUUsageThresholdInPercents = 3;
170 const int kMinRasterThreads = 1;
171 const int kMaxRasterThreads = 64;
173 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
174 // incorrectly from the wrong thread.
175 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
176 lazy_tls = LAZY_INSTANCE_INITIALIZER;
178 class RenderViewZoomer : public RenderViewVisitor {
179 public:
180 RenderViewZoomer(const std::string& scheme,
181 const std::string& host,
182 double zoom_level) : scheme_(scheme),
183 host_(host),
184 zoom_level_(zoom_level) {
187 virtual bool Visit(RenderView* render_view) OVERRIDE {
188 WebView* webview = render_view->GetWebView();
189 WebDocument document = webview->mainFrame()->document();
191 // Don't set zoom level for full-page plugin since they don't use the same
192 // zoom settings.
193 if (document.isPluginDocument())
194 return true;
195 GURL url(document.url());
196 // Empty scheme works as wildcard that matches any scheme,
197 if ((net::GetHostOrSpecFromURL(url) == host_) &&
198 (scheme_.empty() || scheme_ == url.scheme())) {
199 webview->setZoomLevel(zoom_level_);
201 return true;
204 private:
205 const std::string scheme_;
206 const std::string host_;
207 const double zoom_level_;
209 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
212 std::string HostToCustomHistogramSuffix(const std::string& host) {
213 if (host == "mail.google.com")
214 return ".gmail";
215 if (host == "docs.google.com" || host == "drive.google.com")
216 return ".docs";
217 if (host == "plus.google.com")
218 return ".plus";
219 return std::string();
222 void* CreateHistogram(
223 const char *name, int min, int max, size_t buckets) {
224 if (min <= 0)
225 min = 1;
226 std::string histogram_name;
227 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
228 if (render_thread_impl) { // Can be null in tests.
229 histogram_name = render_thread_impl->
230 histogram_customizer()->ConvertToCustomHistogramName(name);
231 } else {
232 histogram_name = std::string(name);
234 base::HistogramBase* histogram = base::Histogram::FactoryGet(
235 histogram_name, min, max, buckets,
236 base::Histogram::kUmaTargetedHistogramFlag);
237 return histogram;
240 void AddHistogramSample(void* hist, int sample) {
241 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
242 histogram->Add(sample);
245 scoped_ptr<base::SharedMemory> AllocateSharedMemoryFunction(size_t size) {
246 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size);
249 void EnableBlinkPlatformLogChannels(const std::string& channels) {
250 if (channels.empty())
251 return;
252 base::StringTokenizer t(channels, ", ");
253 while (t.GetNext())
254 blink::enableLogChannel(t.token().c_str());
257 void NotifyTimezoneChangeOnThisThread() {
258 v8::Isolate* isolate = v8::Isolate::GetCurrent();
259 if (!isolate)
260 return;
261 v8::Date::DateTimeConfigurationChangeNotification(isolate);
264 } // namespace
266 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
267 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
268 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
269 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
272 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
274 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
275 const std::string& host, size_t view_count) {
276 if (CommandLine::ForCurrentProcess()->HasSwitch(
277 switches::kDisableHistogramCustomizer)) {
278 return;
280 // Check if all RenderViews are displaying a page from the same host. If there
281 // is only one RenderView, the common host is this view's host. If there are
282 // many, check if this one shares the common host of the other
283 // RenderViews. It's ok to not detect some cases where the RenderViews share a
284 // common host. This information is only used for producing custom histograms.
285 if (view_count == 1)
286 SetCommonHost(host);
287 else if (host != common_host_)
288 SetCommonHost(std::string());
291 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
292 const char* histogram_name) const {
293 std::string name(histogram_name);
294 if (!common_host_histogram_suffix_.empty() &&
295 custom_histograms_.find(name) != custom_histograms_.end())
296 name += common_host_histogram_suffix_;
297 return name;
300 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
301 const std::string& host) {
302 if (host != common_host_) {
303 common_host_ = host;
304 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
305 v8::V8::SetCreateHistogramFunction(CreateHistogram);
309 RenderThreadImpl* RenderThreadImpl::current() {
310 return lazy_tls.Pointer()->Get();
313 // When we run plugins in process, we actually run them on the render thread,
314 // which means that we need to make the render thread pump UI events.
315 RenderThreadImpl::RenderThreadImpl() {
316 Init();
319 RenderThreadImpl::RenderThreadImpl(const std::string& channel_name)
320 : ChildThread(channel_name) {
321 Init();
324 void RenderThreadImpl::Init() {
325 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
327 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
328 base::PlatformThread::CurrentId(),
329 kTraceEventRendererMainThreadSortIndex);
331 v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
332 v8::V8::SetCreateHistogramFunction(CreateHistogram);
333 v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
335 #if defined(OS_MACOSX) || defined(OS_ANDROID)
336 // On Mac and Android, the select popups are rendered by the browser.
337 blink::WebView::setUseExternalPopupMenus(true);
338 #endif
340 lazy_tls.Pointer()->Set(this);
342 // Register this object as the main thread.
343 ChildProcess::current()->set_main_thread(this);
345 // In single process the single process is all there is.
346 suspend_webkit_shared_timer_ = true;
347 notify_webkit_of_modal_loop_ = true;
348 webkit_shared_timer_suspended_ = false;
349 widget_count_ = 0;
350 hidden_widget_count_ = 0;
351 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
352 idle_notifications_to_skip_ = 0;
353 layout_test_mode_ = false;
355 appcache_dispatcher_.reset(
356 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
357 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
358 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
359 thread_safe_sender()));
360 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
362 media_stream_center_ = NULL;
364 db_message_filter_ = new DBMessageFilter();
365 AddFilter(db_message_filter_.get());
367 vc_manager_.reset(new VideoCaptureImplManager());
368 AddFilter(vc_manager_->video_capture_message_filter());
370 #if defined(ENABLE_WEBRTC)
371 peer_connection_tracker_.reset(new PeerConnectionTracker());
372 AddObserver(peer_connection_tracker_.get());
374 p2p_socket_dispatcher_ =
375 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
376 AddFilter(p2p_socket_dispatcher_.get());
378 webrtc_identity_service_.reset(new WebRTCIdentityService());
380 media_stream_factory_.reset(new MediaStreamDependencyFactory(
381 p2p_socket_dispatcher_.get()));
382 AddObserver(media_stream_factory_.get());
383 #endif // defined(ENABLE_WEBRTC)
385 audio_input_message_filter_ =
386 new AudioInputMessageFilter(GetIOMessageLoopProxy());
387 AddFilter(audio_input_message_filter_.get());
389 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
390 AddFilter(audio_message_filter_.get());
392 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
393 AddFilter(midi_message_filter_.get());
395 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
397 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
399 GetContentClient()->renderer()->RenderThreadStarted();
401 InitSkiaEventTracer();
403 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
404 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
405 RegisterExtension(GpuBenchmarkingExtension::Get());
407 is_impl_side_painting_enabled_ =
408 command_line.HasSwitch(switches::kEnableImplSidePainting);
409 webkit::WebLayerImpl::SetImplSidePaintingEnabled(
410 is_impl_side_painting_enabled_);
412 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy) &&
413 !command_line.HasSwitch(switches::kDisableZeroCopy);
415 is_one_copy_enabled_ = command_line.HasSwitch(switches::kEnableOneCopy);
417 if (command_line.HasSwitch(switches::kDisableLCDText)) {
418 is_lcd_text_enabled_ = false;
419 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
420 is_lcd_text_enabled_ = true;
421 } else {
422 #if defined(OS_ANDROID)
423 is_lcd_text_enabled_ = false;
424 #else
425 is_lcd_text_enabled_ = true;
426 #endif
429 is_gpu_rasterization_enabled_ =
430 command_line.HasSwitch(switches::kEnableGpuRasterization);
431 is_gpu_rasterization_forced_ =
432 command_line.HasSwitch(switches::kForceGpuRasterization);
434 is_low_res_tiling_enabled_ = true;
435 if (command_line.HasSwitch(switches::kDisableLowResTiling) &&
436 !command_line.HasSwitch(switches::kEnableLowResTiling)) {
437 is_low_res_tiling_enabled_ = false;
440 // Note that under Linux, the media library will normally already have
441 // been initialized by the Zygote before this instance became a Renderer.
442 base::FilePath media_path;
443 PathService::Get(DIR_MEDIA_LIBS, &media_path);
444 if (!media_path.empty())
445 media::InitializeMediaLibrary(media_path);
447 memory_pressure_listener_.reset(new base::MemoryPressureListener(
448 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
450 std::vector<base::DiscardableMemoryType> supported_types;
451 base::DiscardableMemory::GetSupportedTypes(&supported_types);
452 DCHECK(!supported_types.empty());
454 // The default preferred type is always the first one in list.
455 base::DiscardableMemoryType type = supported_types[0];
457 if (command_line.HasSwitch(switches::kUseDiscardableMemory)) {
458 std::string requested_type_name = command_line.GetSwitchValueASCII(
459 switches::kUseDiscardableMemory);
460 base::DiscardableMemoryType requested_type =
461 base::DiscardableMemory::GetNamedType(requested_type_name);
462 if (std::find(supported_types.begin(),
463 supported_types.end(),
464 requested_type) != supported_types.end()) {
465 type = requested_type;
466 } else {
467 LOG(ERROR) << "Requested discardable memory type is not supported.";
471 base::DiscardableMemory::SetPreferredType(type);
473 // Allow discardable memory implementations to register memory pressure
474 // listeners.
475 base::DiscardableMemory::RegisterMemoryPressureListeners();
477 // AllocateGpuMemoryBuffer must be used exclusively on one thread but
478 // it doesn't have to be the same thread RenderThreadImpl is created on.
479 allocate_gpu_memory_buffer_thread_checker_.DetachFromThread();
481 if (command_line.HasSwitch(switches::kNumRasterThreads)) {
482 int num_raster_threads;
483 std::string string_value =
484 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
485 if (base::StringToInt(string_value, &num_raster_threads) &&
486 num_raster_threads >= kMinRasterThreads &&
487 num_raster_threads <= kMaxRasterThreads) {
488 cc::RasterWorkerPool::SetNumRasterThreads(num_raster_threads);
489 } else {
490 LOG(WARNING) << "Failed to parse switch " <<
491 switches::kNumRasterThreads << ": " << string_value;
495 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
498 RenderThreadImpl::~RenderThreadImpl() {
501 void RenderThreadImpl::Shutdown() {
502 FOR_EACH_OBSERVER(
503 RenderProcessObserver, observers_, OnRenderProcessShutdown());
505 ChildThread::Shutdown();
507 // Wait for all databases to be closed.
508 if (webkit_platform_support_) {
509 webkit_platform_support_->web_database_observer_impl()->
510 WaitForAllDatabasesToClose();
513 // Shutdown in reverse of the initialization order.
514 if (devtools_agent_message_filter_.get()) {
515 RemoveFilter(devtools_agent_message_filter_.get());
516 devtools_agent_message_filter_ = NULL;
519 RemoveFilter(audio_input_message_filter_.get());
520 audio_input_message_filter_ = NULL;
522 RemoveFilter(audio_message_filter_.get());
523 audio_message_filter_ = NULL;
525 // |media_stream_factory_| produces users of |vc_manager_| so it must be
526 // destroyed first.
527 #if defined(ENABLE_WEBRTC)
528 media_stream_factory_.reset();
529 #endif
530 RemoveFilter(vc_manager_->video_capture_message_filter());
531 vc_manager_.reset();
533 RemoveFilter(db_message_filter_.get());
534 db_message_filter_ = NULL;
536 // Shutdown the file thread if it's running.
537 if (file_thread_)
538 file_thread_->Stop();
540 if (compositor_output_surface_filter_.get()) {
541 RemoveFilter(compositor_output_surface_filter_.get());
542 compositor_output_surface_filter_ = NULL;
545 media_thread_.reset();
546 compositor_thread_.reset();
547 input_handler_manager_.reset();
548 if (input_event_filter_.get()) {
549 RemoveFilter(input_event_filter_.get());
550 input_event_filter_ = NULL;
553 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
554 // hold pointers to V8 objects (e.g., via pending requests).
555 main_thread_indexed_db_dispatcher_.reset();
557 if (webkit_platform_support_)
558 blink::shutdown();
560 lazy_tls.Pointer()->Set(NULL);
562 // TODO(port)
563 #if defined(OS_WIN)
564 // Clean up plugin channels before this thread goes away.
565 NPChannelBase::CleanupChannels();
566 #endif
569 bool RenderThreadImpl::Send(IPC::Message* msg) {
570 // Certain synchronous messages cannot always be processed synchronously by
571 // the browser, e.g., putting up UI and waiting for the user. This could cause
572 // a complete hang of Chrome if a windowed plug-in is trying to communicate
573 // with the renderer thread since the browser's UI thread could be stuck
574 // (within a Windows API call) trying to synchronously communicate with the
575 // plug-in. The remedy is to pump messages on this thread while the browser
576 // is processing this request. This creates an opportunity for re-entrancy
577 // into WebKit, so we need to take care to disable callbacks, timers, and
578 // pending network loads that could trigger such callbacks.
579 bool pumping_events = false;
580 if (msg->is_sync()) {
581 if (msg->is_caller_pumping_messages()) {
582 pumping_events = true;
586 bool suspend_webkit_shared_timer = true; // default value
587 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
589 bool notify_webkit_of_modal_loop = true; // default value
590 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
592 #if defined(ENABLE_PLUGINS)
593 int render_view_id = MSG_ROUTING_NONE;
594 #endif
596 if (pumping_events) {
597 if (suspend_webkit_shared_timer)
598 webkit_platform_support_->SuspendSharedTimer();
600 if (notify_webkit_of_modal_loop)
601 WebView::willEnterModalLoop();
602 #if defined(ENABLE_PLUGINS)
603 RenderViewImpl* render_view =
604 RenderViewImpl::FromRoutingID(msg->routing_id());
605 if (render_view) {
606 render_view_id = msg->routing_id();
607 PluginChannelHost::Broadcast(
608 new PluginMsg_SignalModalDialogEvent(render_view_id));
610 #endif
613 bool rv = ChildThread::Send(msg);
615 if (pumping_events) {
616 #if defined(ENABLE_PLUGINS)
617 if (render_view_id != MSG_ROUTING_NONE) {
618 PluginChannelHost::Broadcast(
619 new PluginMsg_ResetModalDialogEvent(render_view_id));
621 #endif
623 if (notify_webkit_of_modal_loop)
624 WebView::didExitModalLoop();
626 if (suspend_webkit_shared_timer)
627 webkit_platform_support_->ResumeSharedTimer();
630 return rv;
633 base::MessageLoop* RenderThreadImpl::GetMessageLoop() {
634 return message_loop();
637 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
638 return channel();
641 std::string RenderThreadImpl::GetLocale() {
642 // The browser process should have passed the locale to the renderer via the
643 // --lang command line flag.
644 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
645 const std::string& lang =
646 parsed_command_line.GetSwitchValueASCII(switches::kLang);
647 DCHECK(!lang.empty());
648 return lang;
651 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
652 return sync_message_filter();
655 scoped_refptr<base::MessageLoopProxy>
656 RenderThreadImpl::GetIOMessageLoopProxy() {
657 return ChildProcess::current()->io_message_loop_proxy();
660 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
661 ChildThread::GetRouter()->AddRoute(routing_id, listener);
664 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
665 ChildThread::GetRouter()->RemoveRoute(routing_id);
668 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
669 IPC::Listener* listener) {
670 AddRoute(routing_id, listener);
671 if (devtools_agent_message_filter_.get()) {
672 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
673 routing_id);
677 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
678 RemoveRoute(routing_id);
679 if (devtools_agent_message_filter_.get()) {
680 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
681 routing_id);
685 int RenderThreadImpl::GenerateRoutingID() {
686 int routing_id = MSG_ROUTING_NONE;
687 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
688 return routing_id;
691 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
692 channel()->AddFilter(filter);
695 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
696 channel()->RemoveFilter(filter);
699 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
700 observers_.AddObserver(observer);
703 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
704 observers_.RemoveObserver(observer);
707 void RenderThreadImpl::SetResourceDispatcherDelegate(
708 ResourceDispatcherDelegate* delegate) {
709 resource_dispatcher()->set_delegate(delegate);
712 void RenderThreadImpl::EnsureWebKitInitialized() {
713 if (webkit_platform_support_)
714 return;
716 webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
717 blink::initialize(webkit_platform_support_.get());
719 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
721 bool enable = command_line.HasSwitch(switches::kEnableThreadedCompositing);
722 if (enable) {
723 #if defined(OS_ANDROID)
724 if (SynchronousCompositorFactory* factory =
725 SynchronousCompositorFactory::GetInstance())
726 compositor_message_loop_proxy_ =
727 factory->GetCompositorMessageLoop();
728 #endif
729 if (!compositor_message_loop_proxy_.get()) {
730 compositor_thread_.reset(new base::Thread("Compositor"));
731 compositor_thread_->Start();
732 #if defined(OS_ANDROID)
733 compositor_thread_->SetPriority(base::kThreadPriority_Display);
734 #endif
735 compositor_message_loop_proxy_ =
736 compositor_thread_->message_loop_proxy();
737 compositor_message_loop_proxy_->PostTask(
738 FROM_HERE,
739 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
740 false));
743 InputHandlerManagerClient* input_handler_manager_client = NULL;
744 #if defined(OS_ANDROID)
745 if (SynchronousCompositorFactory* factory =
746 SynchronousCompositorFactory::GetInstance()) {
747 input_handler_manager_client = factory->GetInputHandlerManagerClient();
749 #endif
750 if (!input_handler_manager_client) {
751 input_event_filter_ =
752 new InputEventFilter(this, compositor_message_loop_proxy_);
753 AddFilter(input_event_filter_.get());
754 input_handler_manager_client = input_event_filter_.get();
756 input_handler_manager_.reset(
757 new InputHandlerManager(compositor_message_loop_proxy_,
758 input_handler_manager_client));
761 scoped_refptr<base::MessageLoopProxy> output_surface_loop;
762 if (enable)
763 output_surface_loop = compositor_message_loop_proxy_;
764 else
765 output_surface_loop = base::MessageLoopProxy::current();
767 compositor_output_surface_filter_ =
768 CompositorOutputSurface::CreateFilter(output_surface_loop.get());
769 AddFilter(compositor_output_surface_filter_.get());
771 RenderThreadImpl::RegisterSchemes();
773 EnableBlinkPlatformLogChannels(
774 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
776 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
778 if (!media::IsMediaLibraryInitialized()) {
779 WebRuntimeFeatures::enableMediaPlayer(false);
780 WebRuntimeFeatures::enableWebAudio(false);
783 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
785 devtools_agent_message_filter_ = new DevToolsAgentFilter();
786 AddFilter(devtools_agent_message_filter_.get());
788 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
789 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
791 webkit::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction);
793 // Limit use of the scaled image cache to when deferred image decoding
794 // is enabled.
795 // TODO(reveman): Allow use of this cache on Android once
796 // SkDiscardablePixelRef is used for decoded images. crbug.com/330041
797 bool use_skia_scaled_image_cache = false;
798 #if !defined(OS_ANDROID)
799 use_skia_scaled_image_cache =
800 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
801 is_impl_side_painting_enabled_;
802 #endif
803 if (!use_skia_scaled_image_cache)
804 SkGraphics::SetImageCacheByteLimit(0u);
807 void RenderThreadImpl::RegisterSchemes() {
808 // swappedout: pages should not be accessible, and should also
809 // be treated as empty documents that can commit synchronously.
810 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
811 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
812 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
815 void RenderThreadImpl::NotifyTimezoneChange() {
816 NotifyTimezoneChangeOnThisThread();
817 RenderThread::Get()->PostTaskToAllWebWorkers(
818 base::Bind(&NotifyTimezoneChangeOnThisThread));
821 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
822 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
825 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
826 Send(new ViewHostMsg_UserMetricsRecordAction(action));
829 scoped_ptr<base::SharedMemory>
830 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
831 if (size > static_cast<size_t>(std::numeric_limits<int>::max()))
832 return scoped_ptr<base::SharedMemory>();
834 base::SharedMemoryHandle handle;
835 bool success;
836 IPC::Message* message =
837 new ChildProcessHostMsg_SyncAllocateSharedMemory(size, &handle);
839 // Allow calling this from the compositor thread.
840 if (base::MessageLoop::current() == message_loop())
841 success = ChildThread::Send(message);
842 else
843 success = sync_message_filter()->Send(message);
845 if (!success)
846 return scoped_ptr<base::SharedMemory>();
848 if (!base::SharedMemory::IsHandleValid(handle))
849 return scoped_ptr<base::SharedMemory>();
851 return scoped_ptr<base::SharedMemory>(new base::SharedMemory(handle, false));
854 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
855 WebScriptController::registerExtension(extension);
858 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
859 idle_notification_delay_in_ms_ = initial_delay_ms;
860 idle_timer_.Stop();
861 idle_timer_.Start(FROM_HERE,
862 base::TimeDelta::FromMilliseconds(initial_delay_ms),
863 this, &RenderThreadImpl::IdleHandler);
866 void RenderThreadImpl::IdleHandler() {
867 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
868 GetContentClient()->renderer()->
869 RunIdleHandlerWhenWidgetsHidden();
870 if (run_in_foreground_tab) {
871 IdleHandlerInForegroundTab();
872 return;
875 base::allocator::ReleaseFreeMemory();
877 // Continue the idle timer if the webkit shared timer is not suspended or
878 // something is left to do.
879 bool continue_timer = !webkit_shared_timer_suspended_;
881 if (!v8::V8::IdleNotification()) {
882 continue_timer = true;
885 // Schedule next invocation.
886 // Dampen the delay using the algorithm (if delay is in seconds):
887 // delay = delay + 1 / (delay + 2)
888 // Using floor(delay) has a dampening effect such as:
889 // 1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
890 // If the delay is in milliseconds, the above formula is equivalent to:
891 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
892 // which is equivalent to
893 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
894 // Note that idle_notification_delay_in_ms_ would be reset to
895 // kInitialIdleHandlerDelayMs in RenderThreadImpl::WidgetHidden.
896 if (continue_timer) {
897 ScheduleIdleHandler(idle_notification_delay_in_ms_ +
898 1000000 / (idle_notification_delay_in_ms_ + 2000));
900 } else {
901 idle_timer_.Stop();
904 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
907 void RenderThreadImpl::IdleHandlerInForegroundTab() {
908 // Increase the delay in the same way as in IdleHandler,
909 // but make it periodic by reseting it once it is too big.
910 int64 new_delay_ms = idle_notification_delay_in_ms_ +
911 1000000 / (idle_notification_delay_in_ms_ + 2000);
912 if (new_delay_ms >= kLongIdleHandlerDelayMs)
913 new_delay_ms = kShortIdleHandlerDelayMs;
915 if (idle_notifications_to_skip_ > 0) {
916 idle_notifications_to_skip_--;
917 } else {
918 int cpu_usage = 0;
919 Send(new ViewHostMsg_GetCPUUsage(&cpu_usage));
920 // Idle notification hint roughly specifies the expected duration of the
921 // idle pause. We set it proportional to the idle timer delay.
922 int idle_hint = static_cast<int>(new_delay_ms / 10);
923 if (cpu_usage < kIdleCPUUsageThresholdInPercents) {
924 base::allocator::ReleaseFreeMemory();
925 if (v8::V8::IdleNotification(idle_hint)) {
926 // V8 finished collecting garbage.
927 new_delay_ms = kLongIdleHandlerDelayMs;
931 ScheduleIdleHandler(new_delay_ms);
934 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
935 return idle_notification_delay_in_ms_;
938 void RenderThreadImpl::SetIdleNotificationDelayInMs(
939 int64 idle_notification_delay_in_ms) {
940 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
943 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
944 child_histogram_message_filter()->SendHistograms(sequence_number);
947 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
948 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
951 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
952 bool result = false;
953 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
954 return result;
957 void RenderThreadImpl::PostponeIdleNotification() {
958 idle_notifications_to_skip_ = 2;
961 scoped_refptr<media::GpuVideoAcceleratorFactories>
962 RenderThreadImpl::GetGpuFactories() {
963 DCHECK(IsMainThread());
965 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
966 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
967 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
968 scoped_refptr<base::MessageLoopProxy> media_loop_proxy =
969 GetMediaThreadMessageLoopProxy();
970 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
971 if (!gpu_va_context_provider_ ||
972 gpu_va_context_provider_->DestroyedOnMainThread()) {
973 if (!gpu_channel_host) {
974 gpu_channel_host = EstablishGpuChannelSync(
975 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
977 blink::WebGraphicsContext3D::Attributes attributes;
978 bool lose_context_when_out_of_memory = false;
979 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
980 make_scoped_ptr(
981 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
982 gpu_channel_host.get(),
983 attributes,
984 lose_context_when_out_of_memory,
985 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
986 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
987 NULL)),
988 "GPU-VideoAccelerator-Offscreen");
991 if (gpu_va_context_provider_) {
992 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
993 gpu_channel_host, media_loop_proxy, gpu_va_context_provider_);
995 return gpu_factories;
998 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
999 RenderThreadImpl::CreateOffscreenContext3d() {
1000 blink::WebGraphicsContext3D::Attributes attributes;
1001 attributes.shareResources = true;
1002 attributes.depth = false;
1003 attributes.stencil = false;
1004 attributes.antialias = false;
1005 attributes.noAutomaticFlushes = true;
1006 bool lose_context_when_out_of_memory = true;
1008 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1009 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1010 return make_scoped_ptr(
1011 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1012 gpu_channel_host.get(),
1013 attributes,
1014 lose_context_when_out_of_memory,
1015 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1016 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1017 NULL));
1020 scoped_refptr<webkit::gpu::ContextProviderWebContext>
1021 RenderThreadImpl::SharedMainThreadContextProvider() {
1022 DCHECK(IsMainThread());
1023 #if defined(OS_ANDROID)
1024 if (SynchronousCompositorFactory* factory =
1025 SynchronousCompositorFactory::GetInstance())
1026 return factory->GetSharedOffscreenContextProviderForMainThread();
1027 #endif
1029 if (!shared_main_thread_contexts_ ||
1030 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1031 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1032 CreateOffscreenContext3d(), "Offscreen-MainThread");
1034 if (shared_main_thread_contexts_ &&
1035 !shared_main_thread_contexts_->BindToCurrentThread())
1036 shared_main_thread_contexts_ = NULL;
1037 return shared_main_thread_contexts_;
1040 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1041 if (!audio_renderer_mixer_manager_) {
1042 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1043 GetAudioHardwareConfig()));
1046 return audio_renderer_mixer_manager_.get();
1049 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1050 if (!audio_hardware_config_) {
1051 media::AudioParameters input_params;
1052 media::AudioParameters output_params;
1053 Send(new ViewHostMsg_GetAudioHardwareConfig(
1054 &input_params, &output_params));
1056 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1057 input_params, output_params));
1058 audio_message_filter_->SetAudioHardwareConfig(audio_hardware_config_.get());
1061 return audio_hardware_config_.get();
1064 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1065 return ChildProcess::current()->GetShutDownEvent();
1068 #if defined(OS_WIN)
1069 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1070 const base::string16& str) {
1071 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1074 void RenderThreadImpl::PreCacheFont(const LOGFONT& log_font) {
1075 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
1078 void RenderThreadImpl::ReleaseCachedFonts() {
1079 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1082 #endif // OS_WIN
1084 bool RenderThreadImpl::IsMainThread() {
1085 return !!current();
1088 base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1089 return message_loop();
1092 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1093 return io_message_loop_proxy_;
1096 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1097 size_t size) {
1098 return scoped_ptr<base::SharedMemory>(
1099 HostAllocateSharedMemoryBuffer(size));
1102 bool RenderThreadImpl::CreateViewCommandBuffer(
1103 int32 surface_id,
1104 const GPUCreateCommandBufferConfig& init_params,
1105 int32 route_id) {
1106 TRACE_EVENT1("gpu",
1107 "RenderThreadImpl::CreateViewCommandBuffer",
1108 "surface_id",
1109 surface_id);
1111 bool succeeded = false;
1112 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1113 surface_id,
1114 init_params,
1115 route_id,
1116 &succeeded);
1118 // Allow calling this from the compositor thread.
1119 thread_safe_sender()->Send(message);
1121 return succeeded;
1124 void RenderThreadImpl::CreateImage(
1125 gfx::PluginWindowHandle window,
1126 int32 image_id,
1127 const CreateImageCallback& callback) {
1128 NOTREACHED();
1131 void RenderThreadImpl::DeleteImage(int32 image_id, int32 sync_point) {
1132 NOTREACHED();
1135 scoped_ptr<gfx::GpuMemoryBuffer> RenderThreadImpl::AllocateGpuMemoryBuffer(
1136 size_t width,
1137 size_t height,
1138 unsigned internalformat) {
1139 DCHECK(allocate_gpu_memory_buffer_thread_checker_.CalledOnValidThread());
1141 if (!GpuMemoryBufferImpl::IsFormatValid(internalformat))
1142 return scoped_ptr<gfx::GpuMemoryBuffer>();
1144 gfx::GpuMemoryBufferHandle handle;
1145 bool success;
1146 IPC::Message* message =
1147 new ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer(width,
1148 height,
1149 internalformat,
1150 &handle);
1152 // Allow calling this from the compositor thread.
1153 if (base::MessageLoop::current() == message_loop())
1154 success = ChildThread::Send(message);
1155 else
1156 success = sync_message_filter()->Send(message);
1158 if (!success)
1159 return scoped_ptr<gfx::GpuMemoryBuffer>();
1161 return GpuMemoryBufferImpl::Create(
1162 handle,
1163 gfx::Size(width, height),
1164 internalformat).PassAs<gfx::GpuMemoryBuffer>();
1167 void RenderThreadImpl::AcceptConnection(
1168 const mojo::String& service_name,
1169 mojo::ScopedMessagePipeHandle message_pipe) {
1170 // TODO(darin): Invent some kind of registration system to use here.
1171 if (service_name.To<base::StringPiece>() == kRendererService_WebUISetup) {
1172 WebUISetupImpl::Bind(message_pipe.Pass());
1173 } else {
1174 NOTREACHED() << "Unknown service name";
1178 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1179 suspend_webkit_shared_timer_ = false;
1182 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1183 notify_webkit_of_modal_loop_ = false;
1186 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1187 const std::string& host,
1188 double zoom_level) {
1189 RenderViewZoomer zoomer(scheme, host, zoom_level);
1190 RenderView::ForEach(&zoomer);
1193 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1194 ObserverListBase<RenderProcessObserver>::Iterator it(observers_);
1195 RenderProcessObserver* observer;
1196 while ((observer = it.GetNext()) != NULL) {
1197 if (observer->OnControlMessageReceived(msg))
1198 return true;
1201 // Some messages are handled by delegates.
1202 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1203 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1204 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1205 return true;
1208 bool handled = true;
1209 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1210 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1211 OnSetZoomLevelForCurrentURL)
1212 // TODO(port): removed from render_messages_internal.h;
1213 // is there a new non-windows message I should add here?
1214 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1215 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1216 IPC_MESSAGE_HANDLER(ViewMsg_NetworkStateChanged, OnNetworkStateChanged)
1217 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1218 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1219 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1220 #if defined(OS_ANDROID)
1221 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1222 OnSetWebKitSharedTimersSuspended)
1223 #endif
1224 #if defined(OS_MACOSX)
1225 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1226 #endif
1227 IPC_MESSAGE_UNHANDLED(handled = false)
1228 IPC_END_MESSAGE_MAP()
1229 return handled;
1232 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1233 EnsureWebKitInitialized();
1234 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1235 RenderViewImpl::Create(params.opener_route_id,
1236 params.window_was_created_with_opener,
1237 params.renderer_preferences,
1238 params.web_preferences,
1239 params.view_id,
1240 params.main_frame_routing_id,
1241 params.surface_id,
1242 params.session_storage_namespace_id,
1243 params.frame_name,
1244 false,
1245 params.swapped_out,
1246 params.hidden,
1247 params.never_visible,
1248 params.next_page_id,
1249 params.screen_info,
1250 params.accessibility_mode);
1253 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1254 CauseForGpuLaunch cause_for_gpu_launch) {
1255 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1257 if (gpu_channel_.get()) {
1258 // Do nothing if we already have a GPU channel or are already
1259 // establishing one.
1260 if (!gpu_channel_->IsLost())
1261 return gpu_channel_.get();
1263 // Recreate the channel if it has been lost.
1264 gpu_channel_ = NULL;
1267 // Ask the browser for the channel name.
1268 int client_id = 0;
1269 IPC::ChannelHandle channel_handle;
1270 gpu::GPUInfo gpu_info;
1271 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1272 &client_id,
1273 &channel_handle,
1274 &gpu_info)) ||
1275 #if defined(OS_POSIX)
1276 channel_handle.socket.fd == -1 ||
1277 #endif
1278 channel_handle.name.empty()) {
1279 // Otherwise cancel the connection.
1280 return NULL;
1283 GetContentClient()->SetGpuInfo(gpu_info);
1285 // Cache some variables that are needed on the compositor thread for our
1286 // implementation of GpuChannelHostFactory.
1287 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1289 gpu_channel_ = GpuChannelHost::Create(
1290 this, gpu_info, channel_handle,
1291 ChildProcess::current()->GetShutDownEvent());
1292 return gpu_channel_.get();
1295 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1296 blink::WebMediaStreamCenterClient* client) {
1297 #if defined(OS_ANDROID)
1298 if (CommandLine::ForCurrentProcess()->HasSwitch(
1299 switches::kDisableWebRTC))
1300 return NULL;
1301 #endif
1303 #if defined(ENABLE_WEBRTC)
1304 if (!media_stream_center_) {
1305 media_stream_center_ = GetContentClient()->renderer()
1306 ->OverrideCreateWebMediaStreamCenter(client);
1307 if (!media_stream_center_) {
1308 scoped_ptr<MediaStreamCenter> media_stream_center(
1309 new MediaStreamCenter(client, GetMediaStreamDependencyFactory()));
1310 AddObserver(media_stream_center.get());
1311 media_stream_center_ = media_stream_center.release();
1314 #endif
1315 return media_stream_center_;
1318 MediaStreamDependencyFactory*
1319 RenderThreadImpl::GetMediaStreamDependencyFactory() {
1320 return media_stream_factory_.get();
1323 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1324 if (!gpu_channel_.get())
1325 return NULL;
1327 if (gpu_channel_->IsLost())
1328 return NULL;
1330 return gpu_channel_.get();
1333 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1334 EnsureWebKitInitialized();
1335 // The call below will cause a GetPlugins call with refresh=true, but at this
1336 // point we already know that the browser has refreshed its list, so disable
1337 // refresh temporarily to prevent each renderer process causing the list to be
1338 // regenerated.
1339 webkit_platform_support_->set_plugin_refresh_allowed(false);
1340 blink::resetPluginCache(reload_pages);
1341 webkit_platform_support_->set_plugin_refresh_allowed(true);
1343 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1346 void RenderThreadImpl::OnNetworkStateChanged(bool online) {
1347 EnsureWebKitInitialized();
1348 WebNetworkStateNotifier::setOnLine(online);
1349 FOR_EACH_OBSERVER(RenderProcessObserver, observers_,
1350 NetworkStateChanged(online));
1353 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1354 GetContentClient()->SetActiveURL(data);
1355 CHECK(false);
1358 void RenderThreadImpl::OnUpdateTimezone() {
1359 NotifyTimezoneChange();
1363 #if defined(OS_ANDROID)
1364 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1365 if (suspend_webkit_shared_timer_) {
1366 EnsureWebKitInitialized();
1367 if (suspend) {
1368 webkit_platform_support_->SuspendSharedTimer();
1369 } else {
1370 webkit_platform_support_->ResumeSharedTimer();
1372 webkit_shared_timer_suspended_ = suspend;
1375 #endif
1377 #if defined(OS_MACOSX)
1378 void RenderThreadImpl::OnUpdateScrollbarTheme(
1379 float initial_button_delay,
1380 float autoscroll_button_delay,
1381 bool jump_on_track_click,
1382 blink::ScrollerStyle preferred_scroller_style,
1383 bool redraw) {
1384 EnsureWebKitInitialized();
1385 static_cast<WebScrollbarBehaviorImpl*>(
1386 webkit_platform_support_->scrollbarBehavior())->set_jump_on_track_click(
1387 jump_on_track_click);
1388 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1389 autoscroll_button_delay,
1390 preferred_scroller_style,
1391 redraw);
1393 #endif
1395 void RenderThreadImpl::OnCreateNewSharedWorker(
1396 const WorkerProcessMsg_CreateWorker_Params& params) {
1397 // EmbeddedSharedWorkerStub will self-destruct.
1398 new EmbeddedSharedWorkerStub(params.url,
1399 params.name,
1400 params.content_security_policy,
1401 params.security_policy_type,
1402 params.pause_on_start,
1403 params.route_id);
1406 void RenderThreadImpl::OnMemoryPressure(
1407 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1408 base::allocator::ReleaseFreeMemory();
1410 if (memory_pressure_level ==
1411 base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL) {
1412 // Trigger full v8 garbage collection on critical memory notification.
1413 v8::V8::LowMemoryNotification();
1414 // Clear the image cache.
1415 blink::WebImageCache::clear();
1416 // Purge Skia font cache, by setting it to 0 and then again to the previous
1417 // limit.
1418 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1419 SkGraphics::SetFontCacheLimit(font_cache_limit);
1420 } else {
1421 // Otherwise trigger a couple of v8 GCs using IdleNotification.
1422 if (!v8::V8::IdleNotification())
1423 v8::V8::IdleNotification();
1427 scoped_refptr<base::MessageLoopProxy>
1428 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1429 DCHECK(message_loop() == base::MessageLoop::current());
1430 if (!file_thread_) {
1431 file_thread_.reset(new base::Thread("Renderer::FILE"));
1432 file_thread_->Start();
1434 return file_thread_->message_loop_proxy();
1437 scoped_refptr<base::MessageLoopProxy>
1438 RenderThreadImpl::GetMediaThreadMessageLoopProxy() {
1439 DCHECK(message_loop() == base::MessageLoop::current());
1440 if (!media_thread_) {
1441 media_thread_.reset(new base::Thread("Media"));
1442 media_thread_->Start();
1444 #if defined(OS_ANDROID)
1445 renderer_demuxer_ = new RendererDemuxerAndroid();
1446 AddFilter(renderer_demuxer_.get());
1447 #endif
1449 return media_thread_->message_loop_proxy();
1452 void RenderThreadImpl::SetFlingCurveParameters(
1453 const std::vector<float>& new_touchpad,
1454 const std::vector<float>& new_touchscreen) {
1455 webkit_platform_support_->SetFlingCurveParameters(new_touchpad,
1456 new_touchscreen);
1460 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1461 if (!gamepad_shared_memory_reader_)
1462 gamepad_shared_memory_reader_.reset(new GamepadSharedMemoryReader);
1463 gamepad_shared_memory_reader_->SampleGamepads(*data);
1466 void RenderThreadImpl::WidgetCreated() {
1467 widget_count_++;
1470 void RenderThreadImpl::WidgetDestroyed() {
1471 widget_count_--;
1474 void RenderThreadImpl::WidgetHidden() {
1475 DCHECK_LT(hidden_widget_count_, widget_count_);
1476 hidden_widget_count_++;
1478 if (widget_count_ && hidden_widget_count_ == widget_count_) {
1479 #if !defined(SYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE)
1480 // TODO(vollick): Remove this this heavy-handed approach once we're polling
1481 // the real system memory pressure.
1482 base::MemoryPressureListener::NotifyMemoryPressure(
1483 base::MemoryPressureListener::MEMORY_PRESSURE_MODERATE);
1484 #endif
1485 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1486 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1490 void RenderThreadImpl::WidgetRestored() {
1491 DCHECK_GT(hidden_widget_count_, 0);
1492 hidden_widget_count_--;
1494 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1495 return;
1498 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1501 } // namespace content