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