IndexedDBFactory now ForceCloses databases.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blobe267452a4e6e1d97111c7f00014b33aedc602ee5
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_tokenizer.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/threading/thread_local.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "base/values.h"
29 #include "cc/base/switches.h"
30 #include "content/child/appcache/appcache_dispatcher.h"
31 #include "content/child/appcache/appcache_frontend_impl.h"
32 #include "content/child/child_histogram_message_filter.h"
33 #include "content/child/db_message_filter.h"
34 #include "content/child/indexed_db/indexed_db_dispatcher.h"
35 #include "content/child/indexed_db/indexed_db_message_filter.h"
36 #include "content/child/npapi/npobject_util.h"
37 #include "content/child/plugin_messages.h"
38 #include "content/child/resource_dispatcher.h"
39 #include "content/child/runtime_features.h"
40 #include "content/child/thread_safe_sender.h"
41 #include "content/child/web_database_observer_impl.h"
42 #include "content/common/child_process_messages.h"
43 #include "content/common/content_constants_internal.h"
44 #include "content/common/database_messages.h"
45 #include "content/common/dom_storage/dom_storage_messages.h"
46 #include "content/common/gpu/client/context_provider_command_buffer.h"
47 #include "content/common/gpu/client/gpu_channel_host.h"
48 #include "content/common/gpu/client/gpu_memory_buffer_impl.h"
49 #include "content/common/gpu/gpu_messages.h"
50 #include "content/common/gpu/gpu_process_launch_causes.h"
51 #include "content/common/resource_messages.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/common/content_constants.h"
54 #include "content/public/common/content_paths.h"
55 #include "content/public/common/content_switches.h"
56 #include "content/public/common/renderer_preferences.h"
57 #include "content/public/common/url_constants.h"
58 #include "content/public/renderer/content_renderer_client.h"
59 #include "content/public/renderer/render_process_observer.h"
60 #include "content/public/renderer/render_view_visitor.h"
61 #include "content/renderer/devtools/devtools_agent_filter.h"
62 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
63 #include "content/renderer/dom_storage/webstoragearea_impl.h"
64 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
65 #include "content/renderer/gamepad_shared_memory_reader.h"
66 #include "content/renderer/gpu/compositor_output_surface.h"
67 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
68 #include "content/renderer/input/input_event_filter.h"
69 #include "content/renderer/input/input_handler_manager.h"
70 #include "content/renderer/media/audio_input_message_filter.h"
71 #include "content/renderer/media/audio_message_filter.h"
72 #include "content/renderer/media/audio_renderer_mixer_manager.h"
73 #include "content/renderer/media/media_stream_center.h"
74 #include "content/renderer/media/media_stream_dependency_factory.h"
75 #include "content/renderer/media/midi_message_filter.h"
76 #include "content/renderer/media/peer_connection_tracker.h"
77 #include "content/renderer/media/video_capture_impl_manager.h"
78 #include "content/renderer/media/video_capture_message_filter.h"
79 #include "content/renderer/media/webrtc_identity_service.h"
80 #include "content/renderer/memory_benchmarking_extension.h"
81 #include "content/renderer/p2p/socket_dispatcher.h"
82 #include "content/renderer/render_process_impl.h"
83 #include "content/renderer/render_view_impl.h"
84 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
85 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
86 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
87 #include "content/renderer/skia_benchmarking_extension.h"
88 #include "grit/content_resources.h"
89 #include "ipc/ipc_channel_handle.h"
90 #include "ipc/ipc_forwarding_message_filter.h"
91 #include "ipc/ipc_platform_file.h"
92 #include "media/base/audio_hardware_config.h"
93 #include "media/base/media.h"
94 #include "media/filters/gpu_video_accelerator_factories.h"
95 #include "net/base/net_errors.h"
96 #include "net/base/net_util.h"
97 #include "third_party/WebKit/public/platform/WebString.h"
98 #include "third_party/WebKit/public/web/WebColorName.h"
99 #include "third_party/WebKit/public/web/WebDatabase.h"
100 #include "third_party/WebKit/public/web/WebDocument.h"
101 #include "third_party/WebKit/public/web/WebFrame.h"
102 #include "third_party/WebKit/public/web/WebImageCache.h"
103 #include "third_party/WebKit/public/web/WebKit.h"
104 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
105 #include "third_party/WebKit/public/web/WebPopupMenu.h"
106 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
107 #include "third_party/WebKit/public/web/WebScriptController.h"
108 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
109 #include "third_party/WebKit/public/web/WebView.h"
110 #include "third_party/skia/include/core/SkGraphics.h"
111 #include "ui/base/layout.h"
112 #include "ui/base/ui_base_switches.h"
113 #include "v8/include/v8.h"
114 #include "webkit/child/worker_task_runner.h"
115 #include "webkit/renderer/compositor_bindings/web_external_bitmap_impl.h"
117 #if defined(OS_WIN)
118 #include <windows.h>
119 #include <objbase.h>
120 #else
121 // TODO(port)
122 #include "base/memory/scoped_handle.h"
123 #include "content/child/npapi/np_channel_base.h"
124 #endif
126 #if defined(OS_MACOSX)
127 #include "third_party/WebKit/public/web/mac/WebScrollbarTheme.h"
128 #endif
130 #if defined(OS_POSIX)
131 #include "ipc/ipc_channel_posix.h"
132 #endif
134 #if defined(OS_ANDROID)
135 #include <cpu-features.h>
136 #include "content/renderer/android/synchronous_compositor_factory.h"
137 #include "content/renderer/media/android/renderer_demuxer_android.h"
138 #endif
140 #if defined(ENABLE_PLUGINS)
141 #include "content/renderer/npapi/plugin_channel_host.h"
142 #endif
144 using base::ThreadRestrictions;
145 using blink::WebDocument;
146 using blink::WebFrame;
147 using blink::WebNetworkStateNotifier;
148 using blink::WebRuntimeFeatures;
149 using blink::WebScriptController;
150 using blink::WebSecurityPolicy;
151 using blink::WebString;
152 using blink::WebView;
154 namespace content {
156 namespace {
158 const int64 kInitialIdleHandlerDelayMs = 1000;
159 const int64 kShortIdleHandlerDelayMs = 1000;
160 const int64 kLongIdleHandlerDelayMs = 30*1000;
161 const int kIdleCPUUsageThresholdInPercents = 3;
163 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
164 // incorrectly from the wrong thread.
165 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
166 lazy_tls = LAZY_INSTANCE_INITIALIZER;
168 class RenderViewZoomer : public RenderViewVisitor {
169 public:
170 RenderViewZoomer(const std::string& scheme,
171 const std::string& host,
172 double zoom_level) : scheme_(scheme),
173 host_(host),
174 zoom_level_(zoom_level) {
177 virtual bool Visit(RenderView* render_view) OVERRIDE {
178 WebView* webview = render_view->GetWebView();
179 WebDocument document = webview->mainFrame()->document();
181 // Don't set zoom level for full-page plugin since they don't use the same
182 // zoom settings.
183 if (document.isPluginDocument())
184 return true;
185 GURL url(document.url());
186 // Empty scheme works as wildcard that matches any scheme,
187 if ((net::GetHostOrSpecFromURL(url) == host_) &&
188 (scheme_.empty() || scheme_ == url.scheme())) {
189 webview->setZoomLevel(zoom_level_);
191 return true;
194 private:
195 const std::string scheme_;
196 const std::string host_;
197 const double zoom_level_;
199 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
202 std::string HostToCustomHistogramSuffix(const std::string& host) {
203 if (host == "mail.google.com")
204 return ".gmail";
205 if (host == "docs.google.com" || host == "drive.google.com")
206 return ".docs";
207 if (host == "plus.google.com")
208 return ".plus";
209 return std::string();
212 void* CreateHistogram(
213 const char *name, int min, int max, size_t buckets) {
214 if (min <= 0)
215 min = 1;
216 std::string histogram_name;
217 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
218 if (render_thread_impl) { // Can be null in tests.
219 histogram_name = render_thread_impl->
220 histogram_customizer()->ConvertToCustomHistogramName(name);
221 } else {
222 histogram_name = std::string(name);
224 base::HistogramBase* histogram = base::Histogram::FactoryGet(
225 histogram_name, min, max, buckets,
226 base::Histogram::kUmaTargetedHistogramFlag);
227 return histogram;
230 void AddHistogramSample(void* hist, int sample) {
231 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
232 histogram->Add(sample);
235 scoped_ptr<base::SharedMemory> AllocateSharedMemoryFunction(size_t size) {
236 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size);
239 void EnableWebCoreLogChannels(const std::string& channels) {
240 if (channels.empty())
241 return;
242 base::StringTokenizer t(channels, ", ");
243 while (t.GetNext())
244 blink::enableLogChannel(t.token().c_str());
247 } // namespace
249 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
250 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
251 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
252 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
255 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
257 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
258 const std::string& host, size_t view_count) {
259 if (CommandLine::ForCurrentProcess()->HasSwitch(
260 switches::kDisableHistogramCustomizer)) {
261 return;
263 // Check if all RenderViews are displaying a page from the same host. If there
264 // is only one RenderView, the common host is this view's host. If there are
265 // many, check if this one shares the common host of the other
266 // RenderViews. It's ok to not detect some cases where the RenderViews share a
267 // common host. This information is only used for producing custom histograms.
268 if (view_count == 1)
269 SetCommonHost(host);
270 else if (host != common_host_)
271 SetCommonHost(std::string());
274 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
275 const char* histogram_name) const {
276 std::string name(histogram_name);
277 if (!common_host_histogram_suffix_.empty() &&
278 custom_histograms_.find(name) != custom_histograms_.end())
279 name += common_host_histogram_suffix_;
280 return name;
283 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
284 const std::string& host) {
285 if (host != common_host_) {
286 common_host_ = host;
287 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
288 v8::V8::SetCreateHistogramFunction(CreateHistogram);
292 RenderThreadImpl* RenderThreadImpl::current() {
293 return lazy_tls.Pointer()->Get();
296 // When we run plugins in process, we actually run them on the render thread,
297 // which means that we need to make the render thread pump UI events.
298 RenderThreadImpl::RenderThreadImpl() {
299 Init();
302 RenderThreadImpl::RenderThreadImpl(const std::string& channel_name)
303 : ChildThread(channel_name) {
304 Init();
307 void RenderThreadImpl::Init() {
308 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
310 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
311 base::PlatformThread::CurrentId(),
312 kTraceEventRendererMainThreadSortIndex);
314 v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
315 v8::V8::SetCreateHistogramFunction(CreateHistogram);
316 v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
318 #if defined(OS_MACOSX) || defined(OS_ANDROID)
319 // On Mac and Android, the select popups are rendered by the browser.
320 blink::WebView::setUseExternalPopupMenus(true);
321 #endif
323 lazy_tls.Pointer()->Set(this);
325 // Register this object as the main thread.
326 ChildProcess::current()->set_main_thread(this);
328 // In single process the single process is all there is.
329 suspend_webkit_shared_timer_ = true;
330 notify_webkit_of_modal_loop_ = true;
331 widget_count_ = 0;
332 hidden_widget_count_ = 0;
333 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
334 idle_notifications_to_skip_ = 0;
335 layout_test_mode_ = false;
336 shutdown_event_ = NULL;
338 appcache_dispatcher_.reset(
339 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
340 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
341 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
342 thread_safe_sender()));
343 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
345 media_stream_center_ = NULL;
347 db_message_filter_ = new DBMessageFilter();
348 AddFilter(db_message_filter_.get());
350 vc_manager_.reset(new VideoCaptureImplManager());
351 AddFilter(vc_manager_->video_capture_message_filter());
353 #if defined(ENABLE_WEBRTC)
354 peer_connection_tracker_.reset(new PeerConnectionTracker());
355 AddObserver(peer_connection_tracker_.get());
357 p2p_socket_dispatcher_ =
358 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
359 AddFilter(p2p_socket_dispatcher_.get());
361 webrtc_identity_service_.reset(new WebRTCIdentityService());
363 media_stream_factory_.reset(new MediaStreamDependencyFactory(
364 p2p_socket_dispatcher_.get()));
365 AddObserver(media_stream_factory_.get());
366 #endif // defined(ENABLE_WEBRTC)
368 audio_input_message_filter_ =
369 new AudioInputMessageFilter(GetIOMessageLoopProxy());
370 AddFilter(audio_input_message_filter_.get());
372 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
373 AddFilter(audio_message_filter_.get());
375 midi_message_filter_ = new MIDIMessageFilter(GetIOMessageLoopProxy());
376 AddFilter(midi_message_filter_.get());
378 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
380 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
382 GetContentClient()->renderer()->RenderThreadStarted();
384 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
385 if (command_line.HasSwitch(switches::kEnableGpuBenchmarking))
386 RegisterExtension(GpuBenchmarkingExtension::Get());
388 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
389 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
390 RegisterExtension(MemoryBenchmarkingExtension::Get());
391 #endif // USE_TCMALLOC
393 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking)) {
394 LOG(WARNING) << "Enabling unsafe Skia benchmarking extension.";
395 RegisterExtension(SkiaBenchmarkingExtension::Get());
398 // Note that under Linux, the media library will normally already have
399 // been initialized by the Zygote before this instance became a Renderer.
400 base::FilePath media_path;
401 PathService::Get(DIR_MEDIA_LIBS, &media_path);
402 if (!media_path.empty())
403 media::InitializeMediaLibrary(media_path);
405 memory_pressure_listener_.reset(new base::MemoryPressureListener(
406 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
408 renderer_process_id_ = base::kNullProcessId;
410 std::vector<base::DiscardableMemoryType> supported_types;
411 base::DiscardableMemory::GetSupportedTypes(&supported_types);
412 DCHECK(!supported_types.empty());
414 // The default preferred type is always the first one in list.
415 base::DiscardableMemoryType type = supported_types[0];
417 if (command_line.HasSwitch(switches::kUseDiscardableMemory)) {
418 std::string requested_type_name = command_line.GetSwitchValueASCII(
419 switches::kUseDiscardableMemory);
420 base::DiscardableMemoryType requested_type =
421 base::DiscardableMemory::GetNamedType(requested_type_name);
422 if (std::find(supported_types.begin(),
423 supported_types.end(),
424 requested_type) != supported_types.end()) {
425 type = requested_type;
426 } else {
427 LOG(ERROR) << "Requested discardable memory type is not supported.";
431 base::DiscardableMemory::SetPreferredType(type);
433 // Allow discardable memory implementations to register memory pressure
434 // listeners.
435 base::DiscardableMemory::RegisterMemoryPressureListeners();
437 // AllocateGpuMemoryBuffer must be used exclusively on one thread but
438 // it doesn't have to be the same thread RenderThreadImpl is created on.
439 allocate_gpu_memory_buffer_thread_checker_.DetachFromThread();
441 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
444 RenderThreadImpl::~RenderThreadImpl() {
447 void RenderThreadImpl::Shutdown() {
448 FOR_EACH_OBSERVER(
449 RenderProcessObserver, observers_, OnRenderProcessShutdown());
451 ChildThread::Shutdown();
453 // Wait for all databases to be closed.
454 if (webkit_platform_support_) {
455 webkit_platform_support_->web_database_observer_impl()->
456 WaitForAllDatabasesToClose();
459 // Shutdown in reverse of the initialization order.
460 if (devtools_agent_message_filter_.get()) {
461 RemoveFilter(devtools_agent_message_filter_.get());
462 devtools_agent_message_filter_ = NULL;
465 RemoveFilter(audio_input_message_filter_.get());
466 audio_input_message_filter_ = NULL;
468 RemoveFilter(audio_message_filter_.get());
469 audio_message_filter_ = NULL;
471 // |media_stream_factory_| produces users of |vc_manager_| so it must be
472 // destroyed first.
473 #if defined(ENABLE_WEBRTC)
474 media_stream_factory_.reset();
475 #endif
476 RemoveFilter(vc_manager_->video_capture_message_filter());
477 vc_manager_.reset();
479 RemoveFilter(db_message_filter_.get());
480 db_message_filter_ = NULL;
482 // Shutdown the file thread if it's running.
483 if (file_thread_)
484 file_thread_->Stop();
486 if (compositor_output_surface_filter_.get()) {
487 RemoveFilter(compositor_output_surface_filter_.get());
488 compositor_output_surface_filter_ = NULL;
491 compositor_thread_.reset();
492 input_handler_manager_.reset();
493 if (input_event_filter_.get()) {
494 RemoveFilter(input_event_filter_.get());
495 input_event_filter_ = NULL;
498 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
499 // hold pointers to V8 objects (e.g., via pending requests).
500 main_thread_indexed_db_dispatcher_.reset();
502 if (webkit_platform_support_)
503 blink::shutdown();
505 lazy_tls.Pointer()->Set(NULL);
507 // TODO(port)
508 #if defined(OS_WIN)
509 // Clean up plugin channels before this thread goes away.
510 NPChannelBase::CleanupChannels();
511 #endif
513 // Leak shared contexts on other threads, as we can not get to the correct
514 // thread to destroy them.
515 if (offscreen_compositor_contexts_.get())
516 offscreen_compositor_contexts_->set_leak_on_destroy();
519 bool RenderThreadImpl::Send(IPC::Message* msg) {
520 // Certain synchronous messages cannot always be processed synchronously by
521 // the browser, e.g., putting up UI and waiting for the user. This could cause
522 // a complete hang of Chrome if a windowed plug-in is trying to communicate
523 // with the renderer thread since the browser's UI thread could be stuck
524 // (within a Windows API call) trying to synchronously communicate with the
525 // plug-in. The remedy is to pump messages on this thread while the browser
526 // is processing this request. This creates an opportunity for re-entrancy
527 // into WebKit, so we need to take care to disable callbacks, timers, and
528 // pending network loads that could trigger such callbacks.
529 bool pumping_events = false;
530 if (msg->is_sync()) {
531 if (msg->is_caller_pumping_messages()) {
532 pumping_events = true;
536 bool suspend_webkit_shared_timer = true; // default value
537 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
539 bool notify_webkit_of_modal_loop = true; // default value
540 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
542 #if defined(ENABLE_PLUGINS)
543 int render_view_id = MSG_ROUTING_NONE;
544 #endif
546 if (pumping_events) {
547 if (suspend_webkit_shared_timer)
548 webkit_platform_support_->SuspendSharedTimer();
550 if (notify_webkit_of_modal_loop)
551 WebView::willEnterModalLoop();
552 #if defined(ENABLE_PLUGINS)
553 RenderViewImpl* render_view =
554 RenderViewImpl::FromRoutingID(msg->routing_id());
555 if (render_view) {
556 render_view_id = msg->routing_id();
557 PluginChannelHost::Broadcast(
558 new PluginMsg_SignalModalDialogEvent(render_view_id));
560 #endif
563 bool rv = ChildThread::Send(msg);
565 if (pumping_events) {
566 #if defined(ENABLE_PLUGINS)
567 if (render_view_id != MSG_ROUTING_NONE) {
568 PluginChannelHost::Broadcast(
569 new PluginMsg_ResetModalDialogEvent(render_view_id));
571 #endif
573 if (notify_webkit_of_modal_loop)
574 WebView::didExitModalLoop();
576 if (suspend_webkit_shared_timer)
577 webkit_platform_support_->ResumeSharedTimer();
580 return rv;
583 base::MessageLoop* RenderThreadImpl::GetMessageLoop() {
584 return message_loop();
587 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
588 return channel();
591 std::string RenderThreadImpl::GetLocale() {
592 // The browser process should have passed the locale to the renderer via the
593 // --lang command line flag.
594 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
595 const std::string& lang =
596 parsed_command_line.GetSwitchValueASCII(switches::kLang);
597 DCHECK(!lang.empty());
598 return lang;
601 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
602 return sync_message_filter();
605 scoped_refptr<base::MessageLoopProxy>
606 RenderThreadImpl::GetIOMessageLoopProxy() {
607 return ChildProcess::current()->io_message_loop_proxy();
610 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
611 ChildThread::AddRoute(routing_id, listener);
614 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
615 ChildThread::RemoveRoute(routing_id);
617 int RenderThreadImpl::GenerateRoutingID() {
618 int routing_id = MSG_ROUTING_NONE;
619 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
620 return routing_id;
623 void RenderThreadImpl::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
624 channel()->AddFilter(filter);
627 void RenderThreadImpl::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
628 channel()->RemoveFilter(filter);
631 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
632 observers_.AddObserver(observer);
635 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
636 observers_.RemoveObserver(observer);
639 void RenderThreadImpl::SetResourceDispatcherDelegate(
640 ResourceDispatcherDelegate* delegate) {
641 resource_dispatcher()->set_delegate(delegate);
644 void RenderThreadImpl::EnsureWebKitInitialized() {
645 if (webkit_platform_support_)
646 return;
648 webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
649 blink::initialize(webkit_platform_support_.get());
651 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
653 bool enable = command_line.HasSwitch(switches::kEnableThreadedCompositing);
654 if (enable) {
655 #if defined(OS_ANDROID)
656 if (SynchronousCompositorFactory* factory =
657 SynchronousCompositorFactory::GetInstance())
658 compositor_message_loop_proxy_ =
659 factory->GetCompositorMessageLoop();
660 #endif
661 if (!compositor_message_loop_proxy_.get()) {
662 compositor_thread_.reset(new base::Thread("Compositor"));
663 compositor_thread_->Start();
664 #if defined(OS_ANDROID)
665 compositor_thread_->SetPriority(base::kThreadPriority_Display);
666 #endif
667 compositor_message_loop_proxy_ =
668 compositor_thread_->message_loop_proxy();
669 compositor_message_loop_proxy_->PostTask(
670 FROM_HERE,
671 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
672 false));
675 InputHandlerManagerClient* input_handler_manager_client = NULL;
676 #if defined(OS_ANDROID)
677 if (SynchronousCompositorFactory* factory =
678 SynchronousCompositorFactory::GetInstance()) {
679 input_handler_manager_client = factory->GetInputHandlerManagerClient();
681 #endif
682 if (!input_handler_manager_client) {
683 input_event_filter_ =
684 new InputEventFilter(this, compositor_message_loop_proxy_);
685 AddFilter(input_event_filter_.get());
686 input_handler_manager_client = input_event_filter_.get();
688 input_handler_manager_.reset(
689 new InputHandlerManager(compositor_message_loop_proxy_,
690 input_handler_manager_client));
693 scoped_refptr<base::MessageLoopProxy> output_surface_loop;
694 if (enable)
695 output_surface_loop = compositor_message_loop_proxy_;
696 else
697 output_surface_loop = base::MessageLoopProxy::current();
699 compositor_output_surface_filter_ =
700 CompositorOutputSurface::CreateFilter(output_surface_loop.get());
701 AddFilter(compositor_output_surface_filter_.get());
703 WebScriptController::enableV8SingleThreadMode();
705 RenderThreadImpl::RegisterSchemes();
707 EnableWebCoreLogChannels(
708 command_line.GetSwitchValueASCII(switches::kWebCoreLogChannels));
710 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
712 if (!media::IsMediaLibraryInitialized()) {
713 WebRuntimeFeatures::enableMediaPlayer(false);
714 WebRuntimeFeatures::enableWebAudio(false);
717 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
719 devtools_agent_message_filter_ = new DevToolsAgentFilter();
720 AddFilter(devtools_agent_message_filter_.get());
722 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
723 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
725 webkit::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction);
727 // Limit use of the scaled image cache to when deferred image decoding
728 // is enabled.
729 // TODO(reveman): Allow use of this cache on Android once
730 // SkDiscardablePixelRef is used for decoded images. crbug.com/330041
731 bool use_skia_scaled_image_cache = false;
732 #if !defined(OS_ANDROID)
733 use_skia_scaled_image_cache =
734 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
735 cc::switches::IsImplSidePaintingEnabled();
736 #endif
737 if (!use_skia_scaled_image_cache)
738 SkGraphics::SetImageCacheByteLimit(0u);
741 void RenderThreadImpl::RegisterSchemes() {
742 // swappedout: pages should not be accessible, and should also
743 // be treated as empty documents that can commit synchronously.
744 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
745 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
746 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
749 void RenderThreadImpl::RecordAction(const UserMetricsAction& action) {
750 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
753 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
754 Send(new ViewHostMsg_UserMetricsRecordAction(action));
757 scoped_ptr<base::SharedMemory>
758 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
759 if (size > static_cast<size_t>(std::numeric_limits<int>::max()))
760 return scoped_ptr<base::SharedMemory>();
762 base::SharedMemoryHandle handle;
763 bool success;
764 IPC::Message* message =
765 new ChildProcessHostMsg_SyncAllocateSharedMemory(size, &handle);
767 // Allow calling this from the compositor thread.
768 if (base::MessageLoop::current() == message_loop())
769 success = ChildThread::Send(message);
770 else
771 success = sync_message_filter()->Send(message);
773 if (!success)
774 return scoped_ptr<base::SharedMemory>();
776 if (!base::SharedMemory::IsHandleValid(handle))
777 return scoped_ptr<base::SharedMemory>();
779 return scoped_ptr<base::SharedMemory>(new base::SharedMemory(handle, false));
782 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
783 WebScriptController::registerExtension(extension);
786 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
787 idle_notification_delay_in_ms_ = initial_delay_ms;
788 idle_timer_.Stop();
789 idle_timer_.Start(FROM_HERE,
790 base::TimeDelta::FromMilliseconds(initial_delay_ms),
791 this, &RenderThreadImpl::IdleHandler);
794 void RenderThreadImpl::IdleHandler() {
795 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
796 GetContentClient()->renderer()->
797 RunIdleHandlerWhenWidgetsHidden();
798 if (run_in_foreground_tab) {
799 IdleHandlerInForegroundTab();
800 return;
803 base::allocator::ReleaseFreeMemory();
805 v8::V8::IdleNotification();
807 // Schedule next invocation.
808 // Dampen the delay using the algorithm (if delay is in seconds):
809 // delay = delay + 1 / (delay + 2)
810 // Using floor(delay) has a dampening effect such as:
811 // 1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
812 // If the delay is in milliseconds, the above formula is equivalent to:
813 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
814 // which is equivalent to
815 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
816 // Note that idle_notification_delay_in_ms_ would be reset to
817 // kInitialIdleHandlerDelayMs in RenderThreadImpl::WidgetHidden.
818 ScheduleIdleHandler(idle_notification_delay_in_ms_ +
819 1000000 / (idle_notification_delay_in_ms_ + 2000));
821 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
824 void RenderThreadImpl::IdleHandlerInForegroundTab() {
825 // Increase the delay in the same way as in IdleHandler,
826 // but make it periodic by reseting it once it is too big.
827 int64 new_delay_ms = idle_notification_delay_in_ms_ +
828 1000000 / (idle_notification_delay_in_ms_ + 2000);
829 if (new_delay_ms >= kLongIdleHandlerDelayMs)
830 new_delay_ms = kShortIdleHandlerDelayMs;
832 if (idle_notifications_to_skip_ > 0) {
833 idle_notifications_to_skip_--;
834 } else {
835 int cpu_usage = 0;
836 Send(new ViewHostMsg_GetCPUUsage(&cpu_usage));
837 // Idle notification hint roughly specifies the expected duration of the
838 // idle pause. We set it proportional to the idle timer delay.
839 int idle_hint = static_cast<int>(new_delay_ms / 10);
840 if (cpu_usage < kIdleCPUUsageThresholdInPercents) {
841 base::allocator::ReleaseFreeMemory();
842 if (v8::V8::IdleNotification(idle_hint)) {
843 // V8 finished collecting garbage.
844 new_delay_ms = kLongIdleHandlerDelayMs;
848 ScheduleIdleHandler(new_delay_ms);
851 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
852 return idle_notification_delay_in_ms_;
855 void RenderThreadImpl::SetIdleNotificationDelayInMs(
856 int64 idle_notification_delay_in_ms) {
857 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
860 void RenderThreadImpl::ToggleWebKitSharedTimer(bool suspend) {
861 if (suspend_webkit_shared_timer_) {
862 EnsureWebKitInitialized();
863 if (suspend) {
864 webkit_platform_support_->SuspendSharedTimer();
865 } else {
866 webkit_platform_support_->ResumeSharedTimer();
871 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
872 child_histogram_message_filter()->SendHistograms(sequence_number);
875 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
876 return webkit_glue::WorkerTaskRunner::Instance()->PostTaskToAllThreads(
877 closure);
880 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
881 bool result = false;
882 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
883 return result;
886 void RenderThreadImpl::PostponeIdleNotification() {
887 idle_notifications_to_skip_ = 2;
890 scoped_refptr<RendererGpuVideoAcceleratorFactories>
891 RenderThreadImpl::GetGpuFactories() {
892 DCHECK(IsMainThread());
894 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
895 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
896 scoped_refptr<RendererGpuVideoAcceleratorFactories> gpu_factories;
897 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
898 if (!gpu_va_context_provider_ ||
899 gpu_va_context_provider_->DestroyedOnMainThread()) {
900 if (!gpu_channel_host) {
901 gpu_channel_host = EstablishGpuChannelSync(
902 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
904 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
905 make_scoped_ptr(
906 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
907 gpu_channel_host.get(),
908 blink::WebGraphicsContext3D::Attributes(),
909 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
910 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits())),
911 "GPU-VideoAccelerator-Offscreen");
914 if (gpu_channel_host) {
915 gpu_factories = new RendererGpuVideoAcceleratorFactories(
916 gpu_channel_host.get(), gpu_va_context_provider_);
918 return gpu_factories;
921 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
922 RenderThreadImpl::CreateOffscreenContext3d() {
923 blink::WebGraphicsContext3D::Attributes attributes;
924 attributes.shareResources = true;
925 attributes.depth = false;
926 attributes.stencil = false;
927 attributes.antialias = false;
928 attributes.noAutomaticFlushes = true;
930 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
931 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
932 return make_scoped_ptr(
933 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
934 gpu_channel_host.get(),
935 attributes,
936 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
937 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits()));
940 scoped_refptr<cc::ContextProvider>
941 RenderThreadImpl::OffscreenCompositorContextProvider() {
942 DCHECK(IsMainThread());
944 #if defined(OS_ANDROID)
945 if (SynchronousCompositorFactory* factory =
946 SynchronousCompositorFactory::GetInstance()) {
947 if (compositor_message_loop_proxy_)
948 return factory->GetOffscreenContextProviderForCompositorThread();
949 return factory->GetOffscreenContextProviderForMainThread();
951 #endif
953 if (!offscreen_compositor_contexts_.get() ||
954 offscreen_compositor_contexts_->DestroyedOnMainThread()) {
955 offscreen_compositor_contexts_ = ContextProviderCommandBuffer::Create(
956 CreateOffscreenContext3d(),
957 "Compositor-Offscreen");
959 return offscreen_compositor_contexts_;
962 scoped_refptr<cc::ContextProvider>
963 RenderThreadImpl::SharedMainThreadContextProvider() {
964 DCHECK(IsMainThread());
965 #if defined(OS_ANDROID)
966 if (SynchronousCompositorFactory* factory =
967 SynchronousCompositorFactory::GetInstance())
968 return factory->GetOffscreenContextProviderForMainThread();
969 #endif
971 if (!shared_main_thread_contexts_ ||
972 shared_main_thread_contexts_->DestroyedOnMainThread()) {
973 if (compositor_message_loop_proxy_) {
974 // In threaded compositing mode, we have to create a new ContextProvider
975 // to bind to the main thread since the compositor's is bound to the
976 // compositor thread.
977 shared_main_thread_contexts_ =
978 ContextProviderCommandBuffer::Create(CreateOffscreenContext3d(),
979 "Offscreen-MainThread");
980 } else {
981 // In single threaded mode, we can use the same context provider.
982 shared_main_thread_contexts_ =
983 static_cast<ContextProviderCommandBuffer*>(
984 OffscreenCompositorContextProvider().get());
987 if (shared_main_thread_contexts_ &&
988 !shared_main_thread_contexts_->BindToCurrentThread())
989 shared_main_thread_contexts_ = NULL;
990 return shared_main_thread_contexts_;
993 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
994 if (!audio_renderer_mixer_manager_) {
995 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
996 GetAudioHardwareConfig()));
999 return audio_renderer_mixer_manager_.get();
1002 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1003 if (!audio_hardware_config_) {
1004 media::AudioParameters input_params;
1005 media::AudioParameters output_params;
1006 Send(new ViewHostMsg_GetAudioHardwareConfig(
1007 &input_params, &output_params));
1009 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1010 input_params, output_params));
1011 audio_message_filter_->SetAudioHardwareConfig(audio_hardware_config_.get());
1014 return audio_hardware_config_.get();
1017 #if defined(OS_WIN)
1018 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1019 const base::string16& str) {
1020 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1023 void RenderThreadImpl::PreCacheFont(const LOGFONT& log_font) {
1024 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
1027 void RenderThreadImpl::ReleaseCachedFonts() {
1028 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1031 #endif // OS_WIN
1033 bool RenderThreadImpl::IsMainThread() {
1034 return !!current();
1037 base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1038 return message_loop();
1041 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1042 return io_message_loop_proxy_;
1045 base::WaitableEvent* RenderThreadImpl::GetShutDownEvent() {
1046 return shutdown_event_;
1049 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1050 size_t size) {
1051 return scoped_ptr<base::SharedMemory>(
1052 HostAllocateSharedMemoryBuffer(size));
1055 int32 RenderThreadImpl::CreateViewCommandBuffer(
1056 int32 surface_id, const GPUCreateCommandBufferConfig& init_params) {
1057 TRACE_EVENT1("gpu",
1058 "RenderThreadImpl::CreateViewCommandBuffer",
1059 "surface_id",
1060 surface_id);
1062 int32 route_id = MSG_ROUTING_NONE;
1063 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1064 surface_id,
1065 init_params,
1066 &route_id);
1068 // Allow calling this from the compositor thread.
1069 thread_safe_sender()->Send(message);
1071 return route_id;
1074 void RenderThreadImpl::CreateImage(
1075 gfx::PluginWindowHandle window,
1076 int32 image_id,
1077 const CreateImageCallback& callback) {
1078 NOTREACHED();
1081 void RenderThreadImpl::DeleteImage(int32 image_id, int32 sync_point) {
1082 NOTREACHED();
1085 scoped_ptr<gfx::GpuMemoryBuffer> RenderThreadImpl::AllocateGpuMemoryBuffer(
1086 size_t width,
1087 size_t height,
1088 unsigned internalformat) {
1089 DCHECK(allocate_gpu_memory_buffer_thread_checker_.CalledOnValidThread());
1091 if (!GpuMemoryBufferImpl::IsFormatValid(internalformat))
1092 return scoped_ptr<gfx::GpuMemoryBuffer>();
1094 gfx::GpuMemoryBufferHandle handle;
1095 bool success;
1096 IPC::Message* message =
1097 new ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer(width,
1098 height,
1099 internalformat,
1100 &handle);
1102 // Allow calling this from the compositor thread.
1103 if (base::MessageLoop::current() == message_loop())
1104 success = ChildThread::Send(message);
1105 else
1106 success = sync_message_filter()->Send(message);
1108 if (!success)
1109 return scoped_ptr<gfx::GpuMemoryBuffer>();
1111 return GpuMemoryBufferImpl::Create(
1112 handle,
1113 gfx::Size(width, height),
1114 internalformat).PassAs<gfx::GpuMemoryBuffer>();
1117 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1118 suspend_webkit_shared_timer_ = false;
1121 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1122 notify_webkit_of_modal_loop_ = false;
1125 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1126 const std::string& host,
1127 double zoom_level) {
1128 RenderViewZoomer zoomer(scheme, host, zoom_level);
1129 RenderView::ForEach(&zoomer);
1132 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1133 ObserverListBase<RenderProcessObserver>::Iterator it(observers_);
1134 RenderProcessObserver* observer;
1135 while ((observer = it.GetNext()) != NULL) {
1136 if (observer->OnControlMessageReceived(msg))
1137 return true;
1140 // Some messages are handled by delegates.
1141 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1142 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1143 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1144 return true;
1147 bool handled = true;
1148 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1149 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1150 OnSetZoomLevelForCurrentURL)
1151 // TODO(port): removed from render_messages_internal.h;
1152 // is there a new non-windows message I should add here?
1153 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1154 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1155 IPC_MESSAGE_HANDLER(ViewMsg_NetworkStateChanged, OnNetworkStateChanged)
1156 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1157 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererProcessID, OnSetRendererProcessID)
1158 #if defined(OS_ANDROID)
1159 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1160 OnSetWebKitSharedTimersSuspended)
1161 #endif
1162 #if defined(OS_MACOSX)
1163 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1164 #endif
1165 IPC_MESSAGE_UNHANDLED(handled = false)
1166 IPC_END_MESSAGE_MAP()
1167 return handled;
1170 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1171 EnsureWebKitInitialized();
1172 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1173 RenderViewImpl::Create(
1174 params.opener_route_id,
1175 params.renderer_preferences,
1176 params.web_preferences,
1177 params.view_id,
1178 params.main_frame_routing_id,
1179 params.surface_id,
1180 params.session_storage_namespace_id,
1181 params.frame_name,
1182 false,
1183 params.swapped_out,
1184 params.hidden,
1185 params.next_page_id,
1186 params.screen_info,
1187 params.accessibility_mode,
1188 params.allow_partial_swap);
1191 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1192 CauseForGpuLaunch cause_for_gpu_launch) {
1193 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1195 if (gpu_channel_.get()) {
1196 // Do nothing if we already have a GPU channel or are already
1197 // establishing one.
1198 if (!gpu_channel_->IsLost())
1199 return gpu_channel_.get();
1201 // Recreate the channel if it has been lost.
1202 gpu_channel_ = NULL;
1205 // Ask the browser for the channel name.
1206 int client_id = 0;
1207 IPC::ChannelHandle channel_handle;
1208 gpu::GPUInfo gpu_info;
1209 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1210 &client_id,
1211 &channel_handle,
1212 &gpu_info)) ||
1213 #if defined(OS_POSIX)
1214 channel_handle.socket.fd == -1 ||
1215 #endif
1216 channel_handle.name.empty()) {
1217 // Otherwise cancel the connection.
1218 return NULL;
1221 GetContentClient()->SetGpuInfo(gpu_info);
1223 // Cache some variables that are needed on the compositor thread for our
1224 // implementation of GpuChannelHostFactory.
1225 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1226 shutdown_event_ = ChildProcess::current()->GetShutDownEvent();
1228 gpu_channel_ = GpuChannelHost::Create(
1229 this, 0, gpu_info, channel_handle);
1230 return gpu_channel_.get();
1233 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1234 blink::WebMediaStreamCenterClient* client) {
1235 #if defined(OS_ANDROID)
1236 if (CommandLine::ForCurrentProcess()->HasSwitch(
1237 switches::kDisableWebRTC))
1238 return NULL;
1239 #endif
1241 #if defined(ENABLE_WEBRTC)
1242 if (!media_stream_center_) {
1243 media_stream_center_ = GetContentClient()->renderer()
1244 ->OverrideCreateWebMediaStreamCenter(client);
1245 if (!media_stream_center_) {
1246 scoped_ptr<MediaStreamCenter> media_stream_center(
1247 new MediaStreamCenter(client, GetMediaStreamDependencyFactory()));
1248 AddObserver(media_stream_center.get());
1249 media_stream_center_ = media_stream_center.release();
1252 #endif
1253 return media_stream_center_;
1256 MediaStreamDependencyFactory*
1257 RenderThreadImpl::GetMediaStreamDependencyFactory() {
1258 return media_stream_factory_.get();
1261 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1262 if (!gpu_channel_.get())
1263 return NULL;
1265 if (gpu_channel_->IsLost())
1266 return NULL;
1268 return gpu_channel_.get();
1271 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1272 EnsureWebKitInitialized();
1273 // The call below will cause a GetPlugins call with refresh=true, but at this
1274 // point we already know that the browser has refreshed its list, so disable
1275 // refresh temporarily to prevent each renderer process causing the list to be
1276 // regenerated.
1277 webkit_platform_support_->set_plugin_refresh_allowed(false);
1278 blink::resetPluginCache(reload_pages);
1279 webkit_platform_support_->set_plugin_refresh_allowed(true);
1281 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1284 void RenderThreadImpl::OnNetworkStateChanged(bool online) {
1285 EnsureWebKitInitialized();
1286 WebNetworkStateNotifier::setOnLine(online);
1289 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1290 GetContentClient()->SetActiveURL(data);
1291 CHECK(false);
1294 void RenderThreadImpl::OnSetRendererProcessID(base::ProcessId process_id) {
1295 renderer_process_id_ = process_id;
1298 #if defined(OS_ANDROID)
1299 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1300 ToggleWebKitSharedTimer(suspend);
1302 #endif
1304 #if defined(OS_MACOSX)
1305 void RenderThreadImpl::OnUpdateScrollbarTheme(float initial_button_delay,
1306 float autoscroll_button_delay,
1307 bool jump_on_track_click,
1308 bool redraw) {
1309 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1310 autoscroll_button_delay,
1311 jump_on_track_click,
1312 redraw);
1314 #endif
1316 void RenderThreadImpl::OnMemoryPressure(
1317 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1318 base::allocator::ReleaseFreeMemory();
1320 if (memory_pressure_level ==
1321 base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL) {
1322 // Trigger full v8 garbage collection on critical memory notification.
1323 v8::V8::LowMemoryNotification();
1324 // Clear the image cache.
1325 blink::WebImageCache::clear();
1326 // Purge Skia font cache, by setting it to 0 and then again to the previous
1327 // limit.
1328 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1329 SkGraphics::SetFontCacheLimit(font_cache_limit);
1330 } else {
1331 // Otherwise trigger a couple of v8 GCs using IdleNotification.
1332 if (!v8::V8::IdleNotification())
1333 v8::V8::IdleNotification();
1337 scoped_refptr<base::MessageLoopProxy>
1338 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1339 DCHECK(message_loop() == base::MessageLoop::current());
1340 if (!file_thread_) {
1341 file_thread_.reset(new base::Thread("Renderer::FILE"));
1342 file_thread_->Start();
1344 return file_thread_->message_loop_proxy();
1347 scoped_refptr<base::MessageLoopProxy>
1348 RenderThreadImpl::GetMediaThreadMessageLoopProxy() {
1349 DCHECK(message_loop() == base::MessageLoop::current());
1350 if (!media_thread_) {
1351 media_thread_.reset(new base::Thread("Media"));
1352 media_thread_->Start();
1354 #if defined(OS_ANDROID)
1355 renderer_demuxer_ = new RendererDemuxerAndroid();
1356 AddFilter(renderer_demuxer_.get());
1357 #endif
1359 return media_thread_->message_loop_proxy();
1362 void RenderThreadImpl::SetFlingCurveParameters(
1363 const std::vector<float>& new_touchpad,
1364 const std::vector<float>& new_touchscreen) {
1365 webkit_platform_support_->SetFlingCurveParameters(new_touchpad,
1366 new_touchscreen);
1370 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1371 if (!gamepad_shared_memory_reader_)
1372 gamepad_shared_memory_reader_.reset(new GamepadSharedMemoryReader);
1373 gamepad_shared_memory_reader_->SampleGamepads(*data);
1376 base::ProcessId RenderThreadImpl::renderer_process_id() const {
1377 return renderer_process_id_;
1380 void RenderThreadImpl::WidgetCreated() {
1381 widget_count_++;
1384 void RenderThreadImpl::WidgetDestroyed() {
1385 widget_count_--;
1388 void RenderThreadImpl::WidgetHidden() {
1389 DCHECK_LT(hidden_widget_count_, widget_count_);
1390 hidden_widget_count_++;
1392 if (widget_count_ && hidden_widget_count_ == widget_count_) {
1393 #if !defined(SYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE)
1394 // TODO(vollick): Remove this this heavy-handed approach once we're polling
1395 // the real system memory pressure.
1396 base::MemoryPressureListener::NotifyMemoryPressure(
1397 base::MemoryPressureListener::MEMORY_PRESSURE_MODERATE);
1398 #endif
1399 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1400 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1404 void RenderThreadImpl::WidgetRestored() {
1405 DCHECK_GT(hidden_widget_count_, 0);
1406 hidden_widget_count_--;
1408 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1409 return;
1412 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1415 } // namespace content