render_thread_impl.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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.
4
5#include "content/renderer/render_thread_impl.h"
6
7#include <algorithm>
8#include <limits>
9#include <map>
10#include <vector>
11
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 "content/child/appcache_dispatcher.h"
30#include "content/child/child_histogram_message_filter.h"
31#include "content/child/db_message_filter.h"
32#include "content/child/indexed_db/indexed_db_dispatcher.h"
33#include "content/child/indexed_db/indexed_db_message_filter.h"
34#include "content/child/npapi/npobject_util.h"
35#include "content/child/plugin_messages.h"
36#include "content/child/resource_dispatcher.h"
37#include "content/child/runtime_features.h"
38#include "content/child/thread_safe_sender.h"
39#include "content/child/web_database_observer_impl.h"
40#include "content/common/child_process_messages.h"
41#include "content/common/content_constants_internal.h"
42#include "content/common/database_messages.h"
43#include "content/common/dom_storage_messages.h"
44#include "content/common/gpu/client/context_provider_command_buffer.h"
45#include "content/common/gpu/client/gpu_channel_host.h"
46#include "content/common/gpu/gpu_messages.h"
47#include "content/common/resource_messages.h"
48#include "content/common/view_messages.h"
49#include "content/public/common/content_constants.h"
50#include "content/public/common/content_paths.h"
51#include "content/public/common/content_switches.h"
52#include "content/public/common/renderer_preferences.h"
53#include "content/public/common/url_constants.h"
54#include "content/public/renderer/content_renderer_client.h"
55#include "content/public/renderer/render_process_observer.h"
56#include "content/public/renderer/render_view_visitor.h"
57#include "content/renderer/devtools/devtools_agent_filter.h"
58#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
59#include "content/renderer/dom_storage/webstoragearea_impl.h"
60#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
61#include "content/renderer/gpu/compositor_output_surface.h"
62#include "content/renderer/gpu/gpu_benchmarking_extension.h"
63#include "content/renderer/gpu/input_event_filter.h"
64#include "content/renderer/gpu/input_handler_manager.h"
65#include "content/renderer/media/audio_input_message_filter.h"
66#include "content/renderer/media/audio_message_filter.h"
67#include "content/renderer/media/audio_renderer_mixer_manager.h"
68#include "content/renderer/media/media_stream_center.h"
69#include "content/renderer/media/media_stream_dependency_factory.h"
70#include "content/renderer/media/midi_message_filter.h"
71#include "content/renderer/media/peer_connection_tracker.h"
72#include "content/renderer/media/video_capture_impl_manager.h"
73#include "content/renderer/media/video_capture_message_filter.h"
74#include "content/renderer/media/webrtc_identity_service.h"
75#include "content/renderer/memory_benchmarking_extension.h"
76#include "content/renderer/p2p/socket_dispatcher.h"
77#include "content/renderer/plugin_channel_host.h"
78#include "content/renderer/render_process_impl.h"
79#include "content/renderer/render_process_visibility_manager.h"
80#include "content/renderer/render_view_impl.h"
81#include "content/renderer/renderer_webkitplatformsupport_impl.h"
82#include "content/renderer/skia_benchmarking_extension.h"
83#include "grit/content_resources.h"
84#include "ipc/ipc_channel_handle.h"
85#include "ipc/ipc_forwarding_message_filter.h"
86#include "ipc/ipc_platform_file.h"
87#include "media/base/audio_hardware_config.h"
88#include "media/base/media.h"
89#include "media/filters/gpu_video_decoder_factories.h"
90#include "net/base/net_errors.h"
91#include "net/base/net_util.h"
92#include "third_party/WebKit/public/platform/WebString.h"
93#include "third_party/WebKit/public/web/WebColorName.h"
94#include "third_party/WebKit/public/web/WebDatabase.h"
95#include "third_party/WebKit/public/web/WebDocument.h"
96#include "third_party/WebKit/public/web/WebFrame.h"
97#include "third_party/WebKit/public/web/WebImageCache.h"
98#include "third_party/WebKit/public/web/WebKit.h"
99#include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
100#include "third_party/WebKit/public/web/WebPopupMenu.h"
101#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
102#include "third_party/WebKit/public/web/WebScriptController.h"
103#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
104#include "third_party/WebKit/public/web/WebSharedWorkerRepository.h"
105#include "third_party/WebKit/public/web/WebView.h"
106#include "ui/base/layout.h"
107#include "ui/base/ui_base_switches.h"
108#include "v8/include/v8.h"
109#include "webkit/child/worker_task_runner.h"
110#include "webkit/glue/webkit_glue.h"
111#include "webkit/renderer/appcache/appcache_frontend_impl.h"
112#include "webkit/renderer/compositor_bindings/web_external_bitmap_impl.h"
113
114#if defined(OS_WIN)
115#include <windows.h>
116#include <objbase.h>
117#include "base/win/scoped_com_initializer.h"
118#else
119// TODO(port)
120#include "base/memory/scoped_handle.h"
121#include "content/child/npapi/np_channel_base.h"
122#endif
123
124#if defined(OS_POSIX)
125#include "ipc/ipc_channel_posix.h"
126#endif
127
128#if defined(OS_ANDROID)
129#include <cpu-features.h>
130#include "content/renderer/android/synchronous_compositor_factory.h"
131#endif
132
133using base::ThreadRestrictions;
134using WebKit::WebDocument;
135using WebKit::WebFrame;
136using WebKit::WebNetworkStateNotifier;
137using WebKit::WebRuntimeFeatures;
138using WebKit::WebScriptController;
139using WebKit::WebSecurityPolicy;
140using WebKit::WebString;
141using WebKit::WebView;
142
143namespace content {
144
145namespace {
146
147const int64 kInitialIdleHandlerDelayMs = 1000;
148const int64 kShortIdleHandlerDelayMs = 1000;
149const int64 kLongIdleHandlerDelayMs = 30*1000;
150const int kIdleCPUUsageThresholdInPercents = 3;
151
152// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
153// incorrectly from the wrong thread.
154base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
155    lazy_tls = LAZY_INSTANCE_INITIALIZER;
156
157class RenderViewZoomer : public RenderViewVisitor {
158 public:
159  RenderViewZoomer(const std::string& scheme,
160                   const std::string& host,
161                   double zoom_level) : scheme_(scheme),
162                                        host_(host),
163                                        zoom_level_(zoom_level) {
164  }
165
166  virtual bool Visit(RenderView* render_view) OVERRIDE {
167    WebView* webview = render_view->GetWebView();
168    WebDocument document = webview->mainFrame()->document();
169
170    // Don't set zoom level for full-page plugin since they don't use the same
171    // zoom settings.
172    if (document.isPluginDocument())
173      return true;
174    GURL url(document.url());
175    // Empty scheme works as wildcard that matches any scheme,
176    if ((net::GetHostOrSpecFromURL(url) == host_) &&
177        (scheme_.empty() || scheme_ == url.scheme())) {
178      webview->setZoomLevel(false, zoom_level_);
179    }
180    return true;
181  }
182
183 private:
184  const std::string scheme_;
185  const std::string host_;
186  const double zoom_level_;
187
188  DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
189};
190
191std::string HostToCustomHistogramSuffix(const std::string& host) {
192  if (host == "mail.google.com")
193    return ".gmail";
194  if (host == "docs.google.com" || host == "drive.google.com")
195    return ".docs";
196  if (host == "plus.google.com")
197    return ".plus";
198  return std::string();
199}
200
201void* CreateHistogram(
202    const char *name, int min, int max, size_t buckets) {
203  if (min <= 0)
204    min = 1;
205  std::string histogram_name;
206  RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
207  if (render_thread_impl) {  // Can be null in tests.
208    histogram_name = render_thread_impl->
209        histogram_customizer()->ConvertToCustomHistogramName(name);
210  } else {
211    histogram_name = std::string(name);
212  }
213  base::HistogramBase* histogram = base::Histogram::FactoryGet(
214      histogram_name, min, max, buckets,
215      base::Histogram::kUmaTargetedHistogramFlag);
216  return histogram;
217}
218
219void AddHistogramSample(void* hist, int sample) {
220  base::Histogram* histogram = static_cast<base::Histogram*>(hist);
221  histogram->Add(sample);
222}
223
224scoped_ptr<base::SharedMemory> AllocateSharedMemoryFunction(size_t size) {
225  return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size);
226}
227
228void EnableWebCoreLogChannels(const std::string& channels) {
229  if (channels.empty())
230    return;
231  base::StringTokenizer t(channels, ", ");
232  while (t.GetNext())
233    WebKit::enableLogChannel(t.token().c_str());
234}
235
236}  // namespace
237
238class RenderThreadImpl::GpuVDAContextLostCallback
239    : public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
240 public:
241  GpuVDAContextLostCallback()
242      : main_message_loop_(base::MessageLoopProxy::current()) {}
243  virtual ~GpuVDAContextLostCallback() {}
244  virtual void onContextLost() {
245    main_message_loop_->PostTask(FROM_HERE, base::Bind(
246        &RenderThreadImpl::OnGpuVDAContextLoss));
247  }
248
249 private:
250  scoped_refptr<base::MessageLoopProxy> main_message_loop_;
251};
252
253RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
254  custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
255  custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
256  custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
257}
258
259RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
260
261void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
262    const std::string& host, size_t view_count) {
263  if (CommandLine::ForCurrentProcess()->HasSwitch(
264      switches::kDisableHistogramCustomizer)) {
265    return;
266  }
267  // Check if all RenderViews are displaying a page from the same host. If there
268  // is only one RenderView, the common host is this view's host. If there are
269  // many, check if this one shares the common host of the other
270  // RenderViews. It's ok to not detect some cases where the RenderViews share a
271  // common host. This information is only used for producing custom histograms.
272  if (view_count == 1)
273    SetCommonHost(host);
274  else if (host != common_host_)
275    SetCommonHost(std::string());
276}
277
278std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
279    const char* histogram_name) const {
280  std::string name(histogram_name);
281  if (!common_host_histogram_suffix_.empty() &&
282      custom_histograms_.find(name) != custom_histograms_.end())
283    name += common_host_histogram_suffix_;
284  return name;
285}
286
287void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
288    const std::string& host) {
289  if (host != common_host_) {
290    common_host_ = host;
291    common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
292    v8::V8::SetCreateHistogramFunction(CreateHistogram);
293  }
294}
295
296RenderThreadImpl* RenderThreadImpl::current() {
297  return lazy_tls.Pointer()->Get();
298}
299
300// When we run plugins in process, we actually run them on the render thread,
301// which means that we need to make the render thread pump UI events.
302RenderThreadImpl::RenderThreadImpl() {
303  Init();
304}
305
306RenderThreadImpl::RenderThreadImpl(const std::string& channel_name)
307    : ChildThread(channel_name) {
308  Init();
309}
310
311void RenderThreadImpl::Init() {
312  TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
313
314  base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
315      base::PlatformThread::CurrentId(),
316      kTraceEventRendererMainThreadSortIndex);
317
318  v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
319  v8::V8::SetCreateHistogramFunction(CreateHistogram);
320  v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
321
322#if defined(OS_MACOSX) || defined(OS_ANDROID)
323  // On Mac and Android, the select popups are rendered by the browser.
324  WebKit::WebView::setUseExternalPopupMenus(true);
325#endif
326
327  lazy_tls.Pointer()->Set(this);
328
329#if defined(OS_WIN)
330  // If you are running plugins in this thread you need COM active but in
331  // the normal case you don't.
332  if (RenderProcessImpl::InProcessPlugins())
333    initialize_com_.reset(new base::win::ScopedCOMInitializer());
334#endif
335
336  // Register this object as the main thread.
337  ChildProcess::current()->set_main_thread(this);
338
339  // In single process the single process is all there is.
340  suspend_webkit_shared_timer_ = true;
341  notify_webkit_of_modal_loop_ = true;
342  widget_count_ = 0;
343  hidden_widget_count_ = 0;
344  idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
345  idle_notifications_to_skip_ = 0;
346  layout_test_mode_ = false;
347  shutdown_event_ = NULL;
348
349  appcache_dispatcher_.reset(
350      new AppCacheDispatcher(Get(), new appcache::AppCacheFrontendImpl()));
351  dom_storage_dispatcher_.reset(new DomStorageDispatcher());
352  main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
353      thread_safe_sender()));
354
355  media_stream_center_ = NULL;
356
357  db_message_filter_ = new DBMessageFilter();
358  AddFilter(db_message_filter_.get());
359
360#if defined(ENABLE_WEBRTC)
361  peer_connection_tracker_.reset(new PeerConnectionTracker());
362  AddObserver(peer_connection_tracker_.get());
363
364  p2p_socket_dispatcher_ =
365      new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
366  AddFilter(p2p_socket_dispatcher_.get());
367
368  webrtc_identity_service_.reset(new WebRTCIdentityService());
369#endif  // defined(ENABLE_WEBRTC)
370  vc_manager_ = new VideoCaptureImplManager();
371  AddFilter(vc_manager_->video_capture_message_filter());
372
373  audio_input_message_filter_ =
374      new AudioInputMessageFilter(GetIOMessageLoopProxy());
375  AddFilter(audio_input_message_filter_.get());
376
377  audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
378  AddFilter(audio_message_filter_.get());
379
380  midi_message_filter_ = new MIDIMessageFilter(GetIOMessageLoopProxy());
381  AddFilter(midi_message_filter_.get());
382
383  AddFilter(new IndexedDBMessageFilter(thread_safe_sender()));
384
385  GetContentClient()->renderer()->RenderThreadStarted();
386
387  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
388  if (command_line.HasSwitch(switches::kEnableGpuBenchmarking))
389      RegisterExtension(GpuBenchmarkingExtension::Get());
390
391#if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
392  if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
393    RegisterExtension(MemoryBenchmarkingExtension::Get());
394#endif  // USE_TCMALLOC
395
396  if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking)) {
397    LOG(WARNING) << "Enabling unsafe Skia benchmarking extension.";
398    RegisterExtension(SkiaBenchmarkingExtension::Get());
399  }
400
401  context_lost_cb_.reset(new GpuVDAContextLostCallback());
402
403  // Note that under Linux, the media library will normally already have
404  // been initialized by the Zygote before this instance became a Renderer.
405  base::FilePath media_path;
406  PathService::Get(DIR_MEDIA_LIBS, &media_path);
407  if (!media_path.empty())
408    media::InitializeMediaLibrary(media_path);
409
410  memory_pressure_listener_.reset(new base::MemoryPressureListener(
411      base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
412
413  TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
414}
415
416RenderThreadImpl::~RenderThreadImpl() {
417}
418
419void RenderThreadImpl::Shutdown() {
420  FOR_EACH_OBSERVER(
421      RenderProcessObserver, observers_, OnRenderProcessShutdown());
422
423  ChildThread::Shutdown();
424
425  // Wait for all databases to be closed.
426  if (web_database_observer_impl_)
427    web_database_observer_impl_->WaitForAllDatabasesToClose();
428
429  // Shutdown in reverse of the initialization order.
430  if (devtools_agent_message_filter_.get()) {
431    RemoveFilter(devtools_agent_message_filter_.get());
432    devtools_agent_message_filter_ = NULL;
433  }
434
435  RemoveFilter(audio_input_message_filter_.get());
436  audio_input_message_filter_ = NULL;
437
438  RemoveFilter(audio_message_filter_.get());
439  audio_message_filter_ = NULL;
440
441  RemoveFilter(vc_manager_->video_capture_message_filter());
442
443  RemoveFilter(db_message_filter_.get());
444  db_message_filter_ = NULL;
445
446  // Shutdown the file thread if it's running.
447  if (file_thread_)
448    file_thread_->Stop();
449
450  if (compositor_output_surface_filter_.get()) {
451    RemoveFilter(compositor_output_surface_filter_.get());
452    compositor_output_surface_filter_ = NULL;
453  }
454
455  compositor_thread_.reset();
456  input_handler_manager_.reset();
457  if (input_event_filter_.get()) {
458    RemoveFilter(input_event_filter_.get());
459    input_event_filter_ = NULL;
460  }
461
462  if (webkit_platform_support_)
463    WebKit::shutdown();
464
465  lazy_tls.Pointer()->Set(NULL);
466
467  // TODO(port)
468#if defined(OS_WIN)
469  // Clean up plugin channels before this thread goes away.
470  NPChannelBase::CleanupChannels();
471#endif
472
473  // Leak shared contexts on other threads, as we can not get to the correct
474  // thread to destroy them.
475  if (shared_contexts_compositor_thread_.get())
476    shared_contexts_compositor_thread_->set_leak_on_destroy();
477}
478
479bool RenderThreadImpl::Send(IPC::Message* msg) {
480  // Certain synchronous messages cannot always be processed synchronously by
481  // the browser, e.g., Chrome frame communicating with the embedding browser.
482  // This could cause a complete hang of Chrome if a windowed plug-in is trying
483  // to communicate with the renderer thread since the browser's UI thread
484  // could be stuck (within a Windows API call) trying to synchronously
485  // communicate with the plug-in.  The remedy is to pump messages on this
486  // thread while the browser is processing this request. This creates an
487  // opportunity for re-entrancy into WebKit, so we need to take care to disable
488  // callbacks, timers, and pending network loads that could trigger such
489  // callbacks.
490  bool pumping_events = false;
491  if (msg->is_sync()) {
492    if (msg->is_caller_pumping_messages()) {
493      pumping_events = true;
494    } else {
495      if ((msg->type() == ViewHostMsg_GetCookies::ID ||
496           msg->type() == ViewHostMsg_GetRawCookies::ID ||
497           msg->type() == ViewHostMsg_CookiesEnabled::ID) &&
498          GetContentClient()->renderer()->
499              ShouldPumpEventsDuringCookieMessage()) {
500        pumping_events = true;
501      }
502    }
503  }
504
505  bool suspend_webkit_shared_timer = true;  // default value
506  std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
507
508  bool notify_webkit_of_modal_loop = true;  // default value
509  std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
510
511  int render_view_id = MSG_ROUTING_NONE;
512
513  if (pumping_events) {
514    if (suspend_webkit_shared_timer)
515      webkit_platform_support_->SuspendSharedTimer();
516
517    if (notify_webkit_of_modal_loop)
518      WebView::willEnterModalLoop();
519
520    RenderViewImpl* render_view =
521        RenderViewImpl::FromRoutingID(msg->routing_id());
522    if (render_view) {
523      render_view_id = msg->routing_id();
524      PluginChannelHost::Broadcast(
525          new PluginMsg_SignalModalDialogEvent(render_view_id));
526    }
527  }
528
529  bool rv = ChildThread::Send(msg);
530
531  if (pumping_events) {
532    if (render_view_id != MSG_ROUTING_NONE) {
533      PluginChannelHost::Broadcast(
534          new PluginMsg_ResetModalDialogEvent(render_view_id));
535    }
536
537    if (notify_webkit_of_modal_loop)
538      WebView::didExitModalLoop();
539
540    if (suspend_webkit_shared_timer)
541      webkit_platform_support_->ResumeSharedTimer();
542  }
543
544  return rv;
545}
546
547base::MessageLoop* RenderThreadImpl::GetMessageLoop() {
548  return message_loop();
549}
550
551IPC::SyncChannel* RenderThreadImpl::GetChannel() {
552  return channel();
553}
554
555std::string RenderThreadImpl::GetLocale() {
556  // The browser process should have passed the locale to the renderer via the
557  // --lang command line flag.
558  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
559  const std::string& lang =
560      parsed_command_line.GetSwitchValueASCII(switches::kLang);
561  DCHECK(!lang.empty());
562  return lang;
563}
564
565IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
566  return sync_message_filter();
567}
568
569scoped_refptr<base::MessageLoopProxy>
570    RenderThreadImpl::GetIOMessageLoopProxy() {
571  return ChildProcess::current()->io_message_loop_proxy();
572}
573
574void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
575  widget_count_++;
576  return ChildThread::AddRoute(routing_id, listener);
577}
578
579void RenderThreadImpl::RemoveRoute(int32 routing_id) {
580  widget_count_--;
581  return ChildThread::RemoveRoute(routing_id);
582}
583
584int RenderThreadImpl::GenerateRoutingID() {
585  int routing_id = MSG_ROUTING_NONE;
586  Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
587  return routing_id;
588}
589
590void RenderThreadImpl::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
591  channel()->AddFilter(filter);
592}
593
594void RenderThreadImpl::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
595  channel()->RemoveFilter(filter);
596}
597
598void RenderThreadImpl::SetOutgoingMessageFilter(
599    IPC::ChannelProxy::OutgoingMessageFilter* filter) {
600}
601
602void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
603  observers_.AddObserver(observer);
604}
605
606void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
607  observers_.RemoveObserver(observer);
608}
609
610void RenderThreadImpl::SetResourceDispatcherDelegate(
611    ResourceDispatcherDelegate* delegate) {
612  resource_dispatcher()->set_delegate(delegate);
613}
614
615void RenderThreadImpl::WidgetHidden() {
616  DCHECK(hidden_widget_count_ < widget_count_);
617  hidden_widget_count_++;
618
619  RenderProcessVisibilityManager* manager =
620      RenderProcessVisibilityManager::GetInstance();
621  manager->WidgetVisibilityChanged(false);
622
623  if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
624    return;
625  }
626
627  if (widget_count_ && hidden_widget_count_ == widget_count_)
628    ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
629}
630
631void RenderThreadImpl::WidgetRestored() {
632  DCHECK_GT(hidden_widget_count_, 0);
633  hidden_widget_count_--;
634
635  RenderProcessVisibilityManager* manager =
636      RenderProcessVisibilityManager::GetInstance();
637  manager->WidgetVisibilityChanged(true);
638
639  if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
640    return;
641  }
642
643  ScheduleIdleHandler(kLongIdleHandlerDelayMs);
644}
645
646void RenderThreadImpl::EnsureWebKitInitialized() {
647  if (webkit_platform_support_)
648    return;
649
650  webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
651  WebKit::initialize(webkit_platform_support_.get());
652  WebKit::setSharedWorkerRepository(
653      webkit_platform_support_.get()->sharedWorkerRepository());
654
655  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
656
657  bool enable = command_line.HasSwitch(switches::kEnableThreadedCompositing);
658  if (enable) {
659#if defined(OS_ANDROID)
660    if (SynchronousCompositorFactory* factory =
661        SynchronousCompositorFactory::GetInstance())
662      compositor_message_loop_proxy_ =
663          factory->GetCompositorMessageLoop();
664#endif
665    if (!compositor_message_loop_proxy_.get()) {
666      compositor_thread_.reset(new base::Thread("Compositor"));
667      compositor_thread_->Start();
668#if defined(OS_ANDROID)
669      compositor_thread_->SetPriority(base::kThreadPriority_Display);
670#endif
671      compositor_message_loop_proxy_ =
672          compositor_thread_->message_loop_proxy();
673      compositor_message_loop_proxy_->PostTask(
674          FROM_HERE,
675          base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
676                     false));
677    }
678
679    InputHandlerManagerClient* input_handler_manager_client = NULL;
680#if defined(OS_ANDROID)
681    if (SynchronousCompositorFactory* factory =
682        SynchronousCompositorFactory::GetInstance()) {
683      input_handler_manager_client = factory->GetInputHandlerManagerClient();
684    }
685#endif
686    if (!input_handler_manager_client) {
687      input_event_filter_ =
688          new InputEventFilter(this, compositor_message_loop_proxy_);
689      AddFilter(input_event_filter_.get());
690      input_handler_manager_client = input_event_filter_.get();
691    }
692    input_handler_manager_.reset(
693        new InputHandlerManager(compositor_message_loop_proxy_,
694                                input_handler_manager_client));
695  }
696
697  scoped_refptr<base::MessageLoopProxy> output_surface_loop;
698  if (enable)
699    output_surface_loop = compositor_message_loop_proxy_;
700  else
701    output_surface_loop = base::MessageLoopProxy::current();
702
703  compositor_output_surface_filter_ =
704      CompositorOutputSurface::CreateFilter(output_surface_loop.get());
705  AddFilter(compositor_output_surface_filter_.get());
706
707  WebScriptController::enableV8SingleThreadMode();
708
709  RenderThreadImpl::RegisterSchemes();
710
711  EnableWebCoreLogChannels(
712      command_line.GetSwitchValueASCII(switches::kWebCoreLogChannels));
713
714  web_database_observer_impl_.reset(
715      new WebDatabaseObserverImpl(sync_message_filter()));
716  WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
717
718  SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
719
720  if (!media::IsMediaLibraryInitialized()) {
721    WebRuntimeFeatures::enableMediaPlayer(false);
722    WebRuntimeFeatures::enableWebAudio(false);
723  }
724
725  FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
726
727  devtools_agent_message_filter_ = new DevToolsAgentFilter();
728  AddFilter(devtools_agent_message_filter_.get());
729
730  if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
731    ScheduleIdleHandler(kLongIdleHandlerDelayMs);
732
733  webkit::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction);
734}
735
736void RenderThreadImpl::RegisterSchemes() {
737  // swappedout: pages should not be accessible, and should also
738  // be treated as empty documents that can commit synchronously.
739  WebString swappedout_scheme(ASCIIToUTF16(kSwappedOutScheme));
740  WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
741  WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
742}
743
744void RenderThreadImpl::RecordUserMetrics(const std::string& action) {
745  Send(new ViewHostMsg_UserMetricsRecordAction(action));
746}
747
748scoped_ptr<base::SharedMemory>
749    RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
750  if (size > static_cast<size_t>(std::numeric_limits<int>::max()))
751    return scoped_ptr<base::SharedMemory>();
752
753  base::SharedMemoryHandle handle;
754  bool success;
755  IPC::Message* message =
756      new ChildProcessHostMsg_SyncAllocateSharedMemory(size, &handle);
757
758  // Allow calling this from the compositor thread.
759  if (base::MessageLoop::current() == message_loop())
760    success = ChildThread::Send(message);
761  else
762    success = sync_message_filter()->Send(message);
763
764  if (!success)
765    return scoped_ptr<base::SharedMemory>();
766
767  if (!base::SharedMemory::IsHandleValid(handle))
768    return scoped_ptr<base::SharedMemory>();
769
770  return scoped_ptr<base::SharedMemory>(new base::SharedMemory(handle, false));
771}
772
773void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
774  WebScriptController::registerExtension(extension);
775}
776
777void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
778  idle_notification_delay_in_ms_ = initial_delay_ms;
779  idle_timer_.Stop();
780  idle_timer_.Start(FROM_HERE,
781      base::TimeDelta::FromMilliseconds(initial_delay_ms),
782      this, &RenderThreadImpl::IdleHandler);
783}
784
785void RenderThreadImpl::IdleHandler() {
786  bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
787                               GetContentClient()->renderer()->
788                                   RunIdleHandlerWhenWidgetsHidden();
789  if (run_in_foreground_tab) {
790    IdleHandlerInForegroundTab();
791    return;
792  }
793
794  base::allocator::ReleaseFreeMemory();
795
796  v8::V8::IdleNotification();
797
798  // Schedule next invocation.
799  // Dampen the delay using the algorithm (if delay is in seconds):
800  //    delay = delay + 1 / (delay + 2)
801  // Using floor(delay) has a dampening effect such as:
802  //    1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
803  // If the delay is in milliseconds, the above formula is equivalent to:
804  //    delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
805  // which is equivalent to
806  //    delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
807  // Note that idle_notification_delay_in_ms_ would be reset to
808  // kInitialIdleHandlerDelayMs in RenderThreadImpl::WidgetHidden.
809  ScheduleIdleHandler(idle_notification_delay_in_ms_ +
810                      1000000 / (idle_notification_delay_in_ms_ + 2000));
811
812  FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
813}
814
815void RenderThreadImpl::IdleHandlerInForegroundTab() {
816  // Increase the delay in the same way as in IdleHandler,
817  // but make it periodic by reseting it once it is too big.
818  int64 new_delay_ms = idle_notification_delay_in_ms_ +
819                       1000000 / (idle_notification_delay_in_ms_ + 2000);
820  if (new_delay_ms >= kLongIdleHandlerDelayMs)
821    new_delay_ms = kShortIdleHandlerDelayMs;
822
823  if (idle_notifications_to_skip_ > 0) {
824    idle_notifications_to_skip_--;
825  } else  {
826    int cpu_usage = 0;
827    Send(new ViewHostMsg_GetCPUUsage(&cpu_usage));
828    // Idle notification hint roughly specifies the expected duration of the
829    // idle pause. We set it proportional to the idle timer delay.
830    int idle_hint = static_cast<int>(new_delay_ms / 10);
831    if (cpu_usage < kIdleCPUUsageThresholdInPercents) {
832      base::allocator::ReleaseFreeMemory();
833      if (v8::V8::IdleNotification(idle_hint)) {
834        // V8 finished collecting garbage.
835        new_delay_ms = kLongIdleHandlerDelayMs;
836      }
837    }
838  }
839  ScheduleIdleHandler(new_delay_ms);
840}
841
842int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
843  return idle_notification_delay_in_ms_;
844}
845
846void RenderThreadImpl::SetIdleNotificationDelayInMs(
847    int64 idle_notification_delay_in_ms) {
848  idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
849}
850
851void RenderThreadImpl::ToggleWebKitSharedTimer(bool suspend) {
852  if (suspend_webkit_shared_timer_) {
853    EnsureWebKitInitialized();
854    if (suspend) {
855      webkit_platform_support_->SuspendSharedTimer();
856    } else {
857      webkit_platform_support_->ResumeSharedTimer();
858    }
859  }
860}
861
862void RenderThreadImpl::UpdateHistograms(int sequence_number) {
863  child_histogram_message_filter()->SendHistograms(sequence_number);
864}
865
866int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
867  return webkit_glue::WorkerTaskRunner::Instance()->PostTaskToAllThreads(
868      closure);
869}
870
871bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
872  bool result = false;
873  Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
874  return result;
875}
876
877void RenderThreadImpl::PostponeIdleNotification() {
878  idle_notifications_to_skip_ = 2;
879}
880
881scoped_refptr<RendererGpuVideoDecoderFactories>
882RenderThreadImpl::GetGpuFactories(
883    const scoped_refptr<base::MessageLoopProxy>& factories_loop) {
884  DCHECK(IsMainThread());
885
886  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
887  scoped_refptr<RendererGpuVideoDecoderFactories> gpu_factories;
888  WebGraphicsContext3DCommandBufferImpl* context3d = NULL;
889  if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode))
890    context3d = GetGpuVDAContext3D();
891  if (context3d) {
892    GpuChannelHost* gpu_channel_host = GetGpuChannel();
893    if (gpu_channel_host) {
894      gpu_factories = new RendererGpuVideoDecoderFactories(
895          gpu_channel_host, factories_loop, context3d);
896    }
897  }
898  return gpu_factories;
899}
900
901/* static */
902void RenderThreadImpl::OnGpuVDAContextLoss() {
903  RenderThreadImpl* self = RenderThreadImpl::current();
904  DCHECK(self);
905  if (!self->gpu_vda_context3d_)
906    return;
907  if (self->compositor_message_loop_proxy().get()) {
908    self->compositor_message_loop_proxy()
909        ->DeleteSoon(FROM_HERE, self->gpu_vda_context3d_.release());
910  } else {
911    self->gpu_vda_context3d_.reset();
912  }
913}
914
915WebGraphicsContext3DCommandBufferImpl*
916RenderThreadImpl::GetGpuVDAContext3D() {
917  if (!gpu_vda_context3d_) {
918    gpu_vda_context3d_.reset(
919        WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
920            this, WebKit::WebGraphicsContext3D::Attributes(),
921            GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D")));
922    if (gpu_vda_context3d_)
923      gpu_vda_context3d_->setContextLostCallback(context_lost_cb_.get());
924  }
925  return gpu_vda_context3d_.get();
926}
927
928scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
929RenderThreadImpl::CreateOffscreenContext3d() {
930  WebKit::WebGraphicsContext3D::Attributes attributes;
931  attributes.shareResources = true;
932  attributes.depth = false;
933  attributes.stencil = false;
934  attributes.antialias = false;
935  attributes.noAutomaticFlushes = true;
936
937  return make_scoped_ptr(
938      WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
939          this,
940          attributes,
941          GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d")));
942}
943
944scoped_refptr<cc::ContextProvider>
945RenderThreadImpl::OffscreenContextProviderForMainThread() {
946  DCHECK(IsMainThread());
947
948#if defined(OS_ANDROID)
949  if (SynchronousCompositorFactory* factory =
950      SynchronousCompositorFactory::GetInstance()) {
951    return factory->GetOffscreenContextProviderForMainThread();
952  }
953#endif
954
955  if (!shared_contexts_main_thread_.get() ||
956      shared_contexts_main_thread_->DestroyedOnMainThread()) {
957    shared_contexts_main_thread_ =
958        ContextProviderCommandBuffer::Create(
959            base::Bind(&RenderThreadImpl::CreateOffscreenContext3d,
960                       base::Unretained(this)));
961    if (shared_contexts_main_thread_.get() &&
962        !shared_contexts_main_thread_->BindToCurrentThread())
963      shared_contexts_main_thread_ = NULL;
964  }
965  return shared_contexts_main_thread_;
966}
967
968scoped_refptr<cc::ContextProvider>
969RenderThreadImpl::OffscreenContextProviderForCompositorThread() {
970  DCHECK(IsMainThread());
971
972#if defined(OS_ANDROID)
973  if (SynchronousCompositorFactory* factory =
974      SynchronousCompositorFactory::GetInstance()) {
975    return factory->GetOffscreenContextProviderForCompositorThread();
976  }
977#endif
978
979  if (!shared_contexts_compositor_thread_.get() ||
980      shared_contexts_compositor_thread_->DestroyedOnMainThread()) {
981    shared_contexts_compositor_thread_ =
982        ContextProviderCommandBuffer::Create(
983            base::Bind(&RenderThreadImpl::CreateOffscreenContext3d,
984                       base::Unretained(this)));
985  }
986  return shared_contexts_compositor_thread_;
987}
988
989AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
990  if (!audio_renderer_mixer_manager_) {
991    audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
992        GetAudioHardwareConfig()));
993  }
994
995  return audio_renderer_mixer_manager_.get();
996}
997
998media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
999  if (!audio_hardware_config_) {
1000    media::AudioParameters input_params;
1001    media::AudioParameters output_params;
1002    Send(new ViewHostMsg_GetAudioHardwareConfig(
1003        &input_params, &output_params));
1004
1005    audio_hardware_config_.reset(new media::AudioHardwareConfig(
1006        input_params, output_params));
1007    audio_message_filter_->SetAudioHardwareConfig(audio_hardware_config_.get());
1008  }
1009
1010  return audio_hardware_config_.get();
1011}
1012
1013#if defined(OS_WIN)
1014void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1015                                              const string16& str) {
1016  Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1017}
1018
1019void RenderThreadImpl::PreCacheFont(const LOGFONT& log_font) {
1020  Send(new ChildProcessHostMsg_PreCacheFont(log_font));
1021}
1022
1023void RenderThreadImpl::ReleaseCachedFonts() {
1024  Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1025}
1026
1027#endif  // OS_WIN
1028
1029bool RenderThreadImpl::IsMainThread() {
1030  return !!current();
1031}
1032
1033base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1034  return message_loop();
1035}
1036
1037scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1038  return io_message_loop_proxy_;
1039}
1040
1041base::WaitableEvent* RenderThreadImpl::GetShutDownEvent() {
1042  return shutdown_event_;
1043}
1044
1045scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1046    size_t size) {
1047  return scoped_ptr<base::SharedMemory>(
1048      HostAllocateSharedMemoryBuffer(size));
1049}
1050
1051int32 RenderThreadImpl::CreateViewCommandBuffer(
1052      int32 surface_id, const GPUCreateCommandBufferConfig& init_params) {
1053  TRACE_EVENT1("gpu",
1054               "RenderThreadImpl::CreateViewCommandBuffer",
1055               "surface_id",
1056               surface_id);
1057
1058  int32 route_id = MSG_ROUTING_NONE;
1059  IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1060      surface_id,
1061      init_params,
1062      &route_id);
1063
1064  // Allow calling this from the compositor thread.
1065  thread_safe_sender()->Send(message);
1066
1067  return route_id;
1068}
1069
1070void RenderThreadImpl::CreateImage(
1071    gfx::PluginWindowHandle window,
1072    int32 image_id,
1073    const CreateImageCallback& callback) {
1074  NOTREACHED();
1075}
1076
1077void RenderThreadImpl::DeleteImage(int32 image_id, int32 sync_point) {
1078  NOTREACHED();
1079}
1080
1081void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1082  suspend_webkit_shared_timer_ = false;
1083}
1084
1085void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1086  notify_webkit_of_modal_loop_ = false;
1087}
1088
1089void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1090                                                   const std::string& host,
1091                                                   double zoom_level) {
1092  RenderViewZoomer zoomer(scheme, host, zoom_level);
1093  RenderView::ForEach(&zoomer);
1094}
1095
1096bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1097  ObserverListBase<RenderProcessObserver>::Iterator it(observers_);
1098  RenderProcessObserver* observer;
1099  while ((observer = it.GetNext()) != NULL) {
1100    if (observer->OnControlMessageReceived(msg))
1101      return true;
1102  }
1103
1104  // Some messages are handled by delegates.
1105  if (appcache_dispatcher_->OnMessageReceived(msg) ||
1106      dom_storage_dispatcher_->OnMessageReceived(msg)) {
1107    return true;
1108  }
1109
1110  bool handled = true;
1111  IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1112    IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1113                        OnSetZoomLevelForCurrentURL)
1114    // TODO(port): removed from render_messages_internal.h;
1115    // is there a new non-windows message I should add here?
1116    IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1117    IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1118    IPC_MESSAGE_HANDLER(ViewMsg_NetworkStateChanged, OnNetworkStateChanged)
1119    IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1120    IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1121                        OnSetWebKitSharedTimersSuspended)
1122    IPC_MESSAGE_UNHANDLED(handled = false)
1123  IPC_END_MESSAGE_MAP()
1124  return handled;
1125}
1126
1127void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1128  EnsureWebKitInitialized();
1129  // When bringing in render_view, also bring in webkit's glue and jsbindings.
1130  RenderViewImpl::Create(
1131      params.opener_route_id,
1132      params.renderer_preferences,
1133      params.web_preferences,
1134      new SharedRenderViewCounter(0),
1135      params.view_id,
1136      params.main_frame_routing_id,
1137      params.surface_id,
1138      params.session_storage_namespace_id,
1139      params.frame_name,
1140      false,
1141      params.swapped_out,
1142      params.next_page_id,
1143      params.screen_info,
1144      params.accessibility_mode,
1145      params.allow_partial_swap);
1146}
1147
1148GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1149    CauseForGpuLaunch cause_for_gpu_launch) {
1150  TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1151
1152  if (gpu_channel_.get()) {
1153    // Do nothing if we already have a GPU channel or are already
1154    // establishing one.
1155    if (!gpu_channel_->IsLost())
1156      return gpu_channel_.get();
1157
1158    // Recreate the channel if it has been lost.
1159    gpu_channel_ = NULL;
1160  }
1161
1162  // Ask the browser for the channel name.
1163  int client_id = 0;
1164  IPC::ChannelHandle channel_handle;
1165  gpu::GPUInfo gpu_info;
1166  if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1167                                               &client_id,
1168                                               &channel_handle,
1169                                               &gpu_info)) ||
1170#if defined(OS_POSIX)
1171      channel_handle.socket.fd == -1 ||
1172#endif
1173      channel_handle.name.empty()) {
1174    // Otherwise cancel the connection.
1175    return NULL;
1176  }
1177
1178  GetContentClient()->SetGpuInfo(gpu_info);
1179
1180  // Cache some variables that are needed on the compositor thread for our
1181  // implementation of GpuChannelHostFactory.
1182  io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1183  shutdown_event_ = ChildProcess::current()->GetShutDownEvent();
1184
1185  gpu_channel_ = GpuChannelHost::Create(
1186      this, 0, client_id, gpu_info, channel_handle);
1187  return gpu_channel_.get();
1188}
1189
1190WebKit::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1191    WebKit::WebMediaStreamCenterClient* client) {
1192#if defined(OS_ANDROID)
1193  if (CommandLine::ForCurrentProcess()->HasSwitch(
1194      switches::kDisableWebRTC))
1195    return NULL;
1196#endif
1197
1198#if defined(ENABLE_WEBRTC)
1199  if (!media_stream_center_) {
1200    media_stream_center_ = GetContentClient()->renderer()
1201        ->OverrideCreateWebMediaStreamCenter(client);
1202    if (!media_stream_center_) {
1203      scoped_ptr<MediaStreamCenter> media_stream_center(
1204          new MediaStreamCenter(client, GetMediaStreamDependencyFactory()));
1205      AddObserver(media_stream_center.get());
1206      media_stream_center_ = media_stream_center.release();
1207    }
1208  }
1209#endif
1210  return media_stream_center_;
1211}
1212
1213MediaStreamDependencyFactory*
1214RenderThreadImpl::GetMediaStreamDependencyFactory() {
1215#if defined(ENABLE_WEBRTC)
1216  if (!media_stream_factory_) {
1217    media_stream_factory_.reset(new MediaStreamDependencyFactory(
1218        vc_manager_.get(), p2p_socket_dispatcher_.get()));
1219  }
1220#endif
1221  return media_stream_factory_.get();
1222}
1223
1224GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1225  if (!gpu_channel_.get())
1226    return NULL;
1227
1228  if (gpu_channel_->IsLost())
1229    return NULL;
1230
1231  return gpu_channel_.get();
1232}
1233
1234void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1235  EnsureWebKitInitialized();
1236  // The call below will cause a GetPlugins call with refresh=true, but at this
1237  // point we already know that the browser has refreshed its list, so disable
1238  // refresh temporarily to prevent each renderer process causing the list to be
1239  // regenerated.
1240  webkit_platform_support_->set_plugin_refresh_allowed(false);
1241  WebKit::resetPluginCache(reload_pages);
1242  webkit_platform_support_->set_plugin_refresh_allowed(true);
1243
1244  FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1245}
1246
1247void RenderThreadImpl::OnNetworkStateChanged(bool online) {
1248  EnsureWebKitInitialized();
1249  WebNetworkStateNotifier::setOnLine(online);
1250}
1251
1252void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1253  GetContentClient()->SetActiveURL(data);
1254  CHECK(false);
1255}
1256
1257void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1258  ToggleWebKitSharedTimer(suspend);
1259}
1260
1261void RenderThreadImpl::OnMemoryPressure(
1262    base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1263  base::allocator::ReleaseFreeMemory();
1264
1265  if (memory_pressure_level ==
1266      base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL) {
1267    // Trigger full v8 garbage collection on critical memory notification.
1268    v8::V8::LowMemoryNotification();
1269    // Clear the image cache.
1270    WebKit::WebImageCache::clear();
1271  } else {
1272    // Otherwise trigger a couple of v8 GCs using IdleNotification.
1273    if (!v8::V8::IdleNotification())
1274      v8::V8::IdleNotification();
1275  }
1276}
1277
1278scoped_refptr<base::MessageLoopProxy>
1279RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1280  DCHECK(message_loop() == base::MessageLoop::current());
1281  if (!file_thread_) {
1282    file_thread_.reset(new base::Thread("Renderer::FILE"));
1283    file_thread_->Start();
1284  }
1285  return file_thread_->message_loop_proxy();
1286}
1287
1288scoped_refptr<base::MessageLoopProxy>
1289RenderThreadImpl::GetMediaThreadMessageLoopProxy() {
1290  DCHECK(message_loop() == base::MessageLoop::current());
1291  if (!media_thread_) {
1292    media_thread_.reset(new base::Thread("Media"));
1293    media_thread_->Start();
1294  }
1295  return media_thread_->message_loop_proxy();
1296}
1297
1298void RenderThreadImpl::SetFlingCurveParameters(
1299    const std::vector<float>& new_touchpad,
1300    const std::vector<float>& new_touchscreen) {
1301  webkit_platform_support_->SetFlingCurveParameters(new_touchpad,
1302                                                    new_touchscreen);
1303
1304}
1305
1306}  // namespace content
1307