[content shell] implement testRunner.overridePreference
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blobce775a8f7c9126b4f77ea09f6fad079fe7c363d8
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/metrics/field_trial.h"
18 #include "base/metrics/histogram.h"
19 #include "base/metrics/stats_table.h"
20 #include "base/path_service.h"
21 #include "base/shared_memory.h"
22 #include "base/string16.h"
23 #include "base/string_number_conversions.h" // Temporary
24 #include "base/threading/thread_local.h"
25 #include "base/utf_string_conversions.h"
26 #include "base/values.h"
27 #include "content/common/appcache/appcache_dispatcher.h"
28 #include "content/common/child_histogram_message_filter.h"
29 #include "content/common/child_process_messages.h"
30 #include "content/common/database_messages.h"
31 #include "content/common/db_message_filter.h"
32 #include "content/common/dom_storage_messages.h"
33 #include "content/common/gpu/client/gpu_channel_host.h"
34 #include "content/common/gpu/gpu_messages.h"
35 #include "content/common/indexed_db/indexed_db_dispatcher.h"
36 #include "content/common/indexed_db/indexed_db_message_filter.h"
37 #include "content/common/npobject_util.h"
38 #include "content/common/plugin_messages.h"
39 #include "content/common/resource_dispatcher.h"
40 #include "content/common/resource_messages.h"
41 #include "content/common/view_messages.h"
42 #include "content/common/web_database_observer_impl.h"
43 #include "content/public/common/content_constants.h"
44 #include "content/public/common/content_paths.h"
45 #include "content/public/common/content_switches.h"
46 #include "content/public/common/renderer_preferences.h"
47 #include "content/public/common/url_constants.h"
48 #include "content/public/renderer/content_renderer_client.h"
49 #include "content/public/renderer/render_process_observer.h"
50 #include "content/public/renderer/render_view_visitor.h"
51 #include "content/renderer/devtools_agent_filter.h"
52 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
53 #include "content/renderer/dom_storage/webstoragearea_impl.h"
54 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
55 #include "content/renderer/gpu/compositor_thread.h"
56 #include "content/renderer/gpu/compositor_output_surface.h"
57 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
58 #include "content/renderer/media/audio_hardware.h"
59 #include "content/renderer/media/audio_input_message_filter.h"
60 #include "content/renderer/media/audio_message_filter.h"
61 #include "content/renderer/media/audio_renderer_mixer_manager.h"
62 #include "content/renderer/media/media_stream_center.h"
63 #include "content/renderer/media/media_stream_dependency_factory.h"
64 #include "content/renderer/media/video_capture_impl_manager.h"
65 #include "content/renderer/media/video_capture_message_filter.h"
66 #include "content/renderer/p2p/socket_dispatcher.h"
67 #include "content/renderer/plugin_channel_host.h"
68 #include "content/renderer/render_process_impl.h"
69 #include "content/renderer/render_view_impl.h"
70 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
71 #include "grit/content_resources.h"
72 #include "ipc/ipc_channel_handle.h"
73 #include "ipc/ipc_forwarding_message_filter.h"
74 #include "ipc/ipc_platform_file.h"
75 #include "media/base/media.h"
76 #include "media/base/media_switches.h"
77 #include "net/base/net_errors.h"
78 #include "net/base/net_util.h"
79 #include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
80 #include "third_party/WebKit/Source/Platform/chromium/public/WebCompositorSupport.h"
81 #include "third_party/WebKit/Source/Platform/chromium/public/WebString.h"
82 #include "third_party/WebKit/Source/WebKit/chromium/public/WebColorName.h"
83 #include "third_party/WebKit/Source/WebKit/chromium/public/WebDatabase.h"
84 #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
85 #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
86 #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
87 #include "third_party/WebKit/Source/WebKit/chromium/public/WebNetworkStateNotifier.h"
88 #include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenu.h"
89 #include "third_party/WebKit/Source/WebKit/chromium/public/WebRuntimeFeatures.h"
90 #include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptController.h"
91 #include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
92 #include "third_party/WebKit/Source/WebKit/chromium/public/WebSharedWorkerRepository.h"
93 #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
94 #include "ui/base/layout.h"
95 #include "ui/base/ui_base_switches.h"
96 #include "v8/include/v8.h"
97 #include "webkit/glue/webkit_glue.h"
99 #if defined(OS_WIN)
100 #include <windows.h>
101 #include <objbase.h>
102 #include "base/win/scoped_com_initializer.h"
103 #else
104 // TODO(port)
105 #include "base/memory/scoped_handle.h"
106 #include "content/common/np_channel_base.h"
107 #endif
109 #if defined(OS_POSIX)
110 #include "ipc/ipc_channel_posix.h"
111 #endif
113 using WebKit::WebDocument;
114 using WebKit::WebFrame;
115 using WebKit::WebNetworkStateNotifier;
116 using WebKit::WebRuntimeFeatures;
117 using WebKit::WebScriptController;
118 using WebKit::WebSecurityPolicy;
119 using WebKit::WebString;
120 using WebKit::WebView;
122 namespace content {
124 namespace {
126 const int64 kInitialIdleHandlerDelayMs = 1000;
127 const int64 kShortIdleHandlerDelayMs = 1000;
128 const int64 kLongIdleHandlerDelayMs = 30*1000;
129 const int kIdleCPUUsageThresholdInPercents = 3;
131 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
132 // incorrectly from the wrong thread.
133 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
134 lazy_tls = LAZY_INSTANCE_INITIALIZER;
136 class RenderViewZoomer : public RenderViewVisitor {
137 public:
138 RenderViewZoomer(const std::string& host, double zoom_level)
139 : host_(host), zoom_level_(zoom_level) {
142 virtual bool Visit(RenderView* render_view) {
143 WebView* webview = render_view->GetWebView();
144 WebDocument document = webview->mainFrame()->document();
146 // Don't set zoom level for full-page plugin since they don't use the same
147 // zoom settings.
148 if (document.isPluginDocument())
149 return true;
151 if (net::GetHostOrSpecFromURL(GURL(document.url())) == host_)
152 webview->setZoomLevel(false, zoom_level_);
153 return true;
156 private:
157 std::string host_;
158 double zoom_level_;
160 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
163 std::string HostToCustomHistogramSuffix(const std::string& host) {
164 if (host == "mail.google.com")
165 return ".gmail";
166 if (host == "docs.google.com" || host == "drive.google.com")
167 return ".docs";
168 if (host == "plus.google.com")
169 return ".plus";
170 return "";
173 void* CreateHistogram(
174 const char *name, int min, int max, size_t buckets) {
175 if (min <= 0)
176 min = 1;
177 std::string histogram_name;
178 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
179 if (render_thread_impl) { // Can be null in tests.
180 histogram_name = render_thread_impl->
181 histogram_customizer()->ConvertToCustomHistogramName(name);
182 } else {
183 histogram_name = std::string(name);
185 base::Histogram* histogram = base::Histogram::FactoryGet(
186 histogram_name, min, max, buckets,
187 base::Histogram::kUmaTargetedHistogramFlag);
188 return histogram;
191 void AddHistogramSample(void* hist, int sample) {
192 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
193 histogram->Add(sample);
196 } // namespace
198 class RenderThreadImpl::GpuVDAContextLostCallback
199 : public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
200 public:
201 GpuVDAContextLostCallback() {}
202 virtual ~GpuVDAContextLostCallback() {}
203 virtual void onContextLost() {
204 ChildThread::current()->message_loop()->PostTask(FROM_HERE, base::Bind(
205 &RenderThreadImpl::OnGpuVDAContextLoss));
209 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
210 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
211 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
212 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
215 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
217 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
218 const std::string& host, size_t view_count) {
219 if (CommandLine::ForCurrentProcess()->HasSwitch(
220 switches::kDisableHistogramCustomizer)) {
221 return;
223 // Check if all RenderViews are displaying a page from the same host. If there
224 // is only one RenderView, the common host is this view's host. If there are
225 // many, check if this one shares the common host of the other
226 // RenderViews. It's ok to not detect some cases where the RenderViews share a
227 // common host. This information is only used for producing custom histograms.
228 if (view_count == 1)
229 SetCommonHost(host);
230 else if (host != common_host_)
231 SetCommonHost(std::string());
234 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
235 const char* histogram_name) const {
236 std::string name(histogram_name);
237 if (!common_host_histogram_suffix_.empty() &&
238 custom_histograms_.find(name) != custom_histograms_.end())
239 name += common_host_histogram_suffix_;
240 return name;
243 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
244 const std::string& host) {
245 if (host != common_host_) {
246 common_host_ = host;
247 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
248 v8::V8::SetCreateHistogramFunction(CreateHistogram);
252 RenderThreadImpl* RenderThreadImpl::current() {
253 return lazy_tls.Pointer()->Get();
256 // When we run plugins in process, we actually run them on the render thread,
257 // which means that we need to make the render thread pump UI events.
258 RenderThreadImpl::RenderThreadImpl() {
259 Init();
262 RenderThreadImpl::RenderThreadImpl(const std::string& channel_name)
263 : ChildThread(channel_name) {
264 Init();
267 void RenderThreadImpl::Init() {
268 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
270 v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
271 v8::V8::SetCreateHistogramFunction(CreateHistogram);
272 v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
274 #if defined(OS_MACOSX) || defined(OS_ANDROID)
275 // On Mac and Android, the select popups are rendered by the browser.
276 WebKit::WebView::setUseExternalPopupMenus(true);
277 #endif
279 lazy_tls.Pointer()->Set(this);
281 #if defined(OS_WIN)
282 // If you are running plugins in this thread you need COM active but in
283 // the normal case you don't.
284 if (RenderProcessImpl::InProcessPlugins())
285 initialize_com_.reset(new base::win::ScopedCOMInitializer());
286 #endif
288 // Register this object as the main thread.
289 ChildProcess::current()->set_main_thread(this);
291 // In single process the single process is all there is.
292 suspend_webkit_shared_timer_ = true;
293 notify_webkit_of_modal_loop_ = true;
294 widget_count_ = 0;
295 hidden_widget_count_ = 0;
296 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
297 idle_notifications_to_skip_ = 0;
298 compositor_initialized_ = false;
300 appcache_dispatcher_.reset(new content::AppCacheDispatcher(Get()));
301 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
302 main_thread_indexed_db_dispatcher_.reset(new content::IndexedDBDispatcher());
304 media_stream_center_ = NULL;
306 db_message_filter_ = new DBMessageFilter();
307 AddFilter(db_message_filter_.get());
309 #if defined(ENABLE_WEBRTC)
310 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOMessageLoopProxy());
311 AddFilter(p2p_socket_dispatcher_);
312 #endif // defined(ENABLE_WEBRTC)
313 vc_manager_ = new VideoCaptureImplManager();
314 AddFilter(vc_manager_->video_capture_message_filter());
316 audio_input_message_filter_ = new AudioInputMessageFilter();
317 AddFilter(audio_input_message_filter_.get());
319 audio_message_filter_ = new AudioMessageFilter();
320 AddFilter(audio_message_filter_.get());
322 AddFilter(new IndexedDBMessageFilter);
324 GetContentClient()->renderer()->RenderThreadStarted();
326 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
327 if (command_line.HasSwitch(switches::kEnableGpuBenchmarking))
328 RegisterExtension(GpuBenchmarkingExtension::Get());
330 context_lost_cb_.reset(new GpuVDAContextLostCallback());
332 // Note that under Linux, the media library will normally already have
333 // been initialized by the Zygote before this instance became a Renderer.
334 FilePath media_path;
335 PathService::Get(DIR_MEDIA_LIBS, &media_path);
336 if (!media_path.empty())
337 media::InitializeMediaLibrary(media_path);
339 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
342 RenderThreadImpl::~RenderThreadImpl() {
343 FOR_EACH_OBSERVER(
344 RenderProcessObserver, observers_, OnRenderProcessShutdown());
346 // Wait for all databases to be closed.
347 if (web_database_observer_impl_.get())
348 web_database_observer_impl_->WaitForAllDatabasesToClose();
350 // Shutdown in reverse of the initialization order.
351 if (devtools_agent_message_filter_.get()) {
352 RemoveFilter(devtools_agent_message_filter_.get());
353 devtools_agent_message_filter_ = NULL;
356 RemoveFilter(audio_input_message_filter_.get());
357 audio_input_message_filter_ = NULL;
359 RemoveFilter(audio_message_filter_.get());
360 audio_message_filter_ = NULL;
362 RemoveFilter(vc_manager_->video_capture_message_filter());
364 RemoveFilter(db_message_filter_.get());
365 db_message_filter_ = NULL;
367 // Shutdown the file thread if it's running.
368 if (file_thread_.get())
369 file_thread_->Stop();
371 if (compositor_output_surface_filter_.get()) {
372 RemoveFilter(compositor_output_surface_filter_.get());
373 compositor_output_surface_filter_ = NULL;
376 if (compositor_initialized_) {
377 WebKit::Platform::current()->compositorSupport()->shutdown();
378 compositor_initialized_ = false;
380 if (compositor_thread_.get()) {
381 RemoveFilter(compositor_thread_->GetMessageFilter());
382 compositor_thread_.reset();
385 if (webkit_platform_support_.get())
386 WebKit::shutdown();
388 lazy_tls.Pointer()->Set(NULL);
390 // TODO(port)
391 #if defined(OS_WIN)
392 // Clean up plugin channels before this thread goes away.
393 NPChannelBase::CleanupChannels();
394 #endif
397 bool RenderThreadImpl::Send(IPC::Message* msg) {
398 // Certain synchronous messages cannot always be processed synchronously by
399 // the browser, e.g., Chrome frame communicating with the embedding browser.
400 // This could cause a complete hang of Chrome if a windowed plug-in is trying
401 // to communicate with the renderer thread since the browser's UI thread
402 // could be stuck (within a Windows API call) trying to synchronously
403 // communicate with the plug-in. The remedy is to pump messages on this
404 // thread while the browser is processing this request. This creates an
405 // opportunity for re-entrancy into WebKit, so we need to take care to disable
406 // callbacks, timers, and pending network loads that could trigger such
407 // callbacks.
408 bool pumping_events = false;
409 if (msg->is_sync()) {
410 if (msg->is_caller_pumping_messages()) {
411 pumping_events = true;
412 } else {
413 if ((msg->type() == ViewHostMsg_GetCookies::ID ||
414 msg->type() == ViewHostMsg_GetRawCookies::ID ||
415 msg->type() == ViewHostMsg_CookiesEnabled::ID) &&
416 GetContentClient()->renderer()->
417 ShouldPumpEventsDuringCookieMessage()) {
418 pumping_events = true;
423 bool suspend_webkit_shared_timer = true; // default value
424 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
426 bool notify_webkit_of_modal_loop = true; // default value
427 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
429 int render_view_id = MSG_ROUTING_NONE;
431 if (pumping_events) {
432 if (suspend_webkit_shared_timer)
433 webkit_platform_support_->SuspendSharedTimer();
435 if (notify_webkit_of_modal_loop)
436 WebView::willEnterModalLoop();
438 RenderWidget* widget =
439 static_cast<RenderWidget*>(ResolveRoute(msg->routing_id()));
440 if (widget) {
441 render_view_id = widget->routing_id();
442 PluginChannelHost::Broadcast(
443 new PluginMsg_SignalModalDialogEvent(render_view_id));
447 bool rv = ChildThread::Send(msg);
449 if (pumping_events) {
450 if (render_view_id != MSG_ROUTING_NONE) {
451 PluginChannelHost::Broadcast(
452 new PluginMsg_ResetModalDialogEvent(render_view_id));
455 if (notify_webkit_of_modal_loop)
456 WebView::didExitModalLoop();
458 if (suspend_webkit_shared_timer)
459 webkit_platform_support_->ResumeSharedTimer();
462 return rv;
465 MessageLoop* RenderThreadImpl::GetMessageLoop() {
466 return message_loop();
469 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
470 return channel();
473 std::string RenderThreadImpl::GetLocale() {
474 // The browser process should have passed the locale to the renderer via the
475 // --lang command line flag.
476 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
477 const std::string& lang =
478 parsed_command_line.GetSwitchValueASCII(switches::kLang);
479 DCHECK(!lang.empty());
480 return lang;
483 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
484 return sync_message_filter();
487 scoped_refptr<base::MessageLoopProxy>
488 RenderThreadImpl::GetIOMessageLoopProxy() {
489 return ChildProcess::current()->io_message_loop_proxy();
492 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
493 widget_count_++;
494 return ChildThread::AddRoute(routing_id, listener);
497 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
498 widget_count_--;
499 return ChildThread::RemoveRoute(routing_id);
502 int RenderThreadImpl::GenerateRoutingID() {
503 int routing_id = MSG_ROUTING_NONE;
504 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
505 return routing_id;
508 void RenderThreadImpl::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
509 channel()->AddFilter(filter);
512 void RenderThreadImpl::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
513 channel()->RemoveFilter(filter);
516 void RenderThreadImpl::SetOutgoingMessageFilter(
517 IPC::ChannelProxy::OutgoingMessageFilter* filter) {
520 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
521 observers_.AddObserver(observer);
524 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
525 observers_.RemoveObserver(observer);
528 void RenderThreadImpl::SetResourceDispatcherDelegate(
529 ResourceDispatcherDelegate* delegate) {
530 resource_dispatcher()->set_delegate(delegate);
533 void RenderThreadImpl::WidgetHidden() {
534 DCHECK(hidden_widget_count_ < widget_count_);
535 hidden_widget_count_++;
537 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
538 return;
541 if (widget_count_ && hidden_widget_count_ == widget_count_)
542 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
545 void RenderThreadImpl::WidgetRestored() {
546 DCHECK_GT(hidden_widget_count_, 0);
547 hidden_widget_count_--;
548 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
549 return;
552 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
555 void RenderThreadImpl::EnsureWebKitInitialized() {
556 if (webkit_platform_support_.get())
557 return;
559 webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
560 WebKit::initialize(webkit_platform_support_.get());
561 WebKit::setSharedWorkerRepository(
562 webkit_platform_support_.get()->sharedWorkerRepository());
564 WebKit::WebCompositorSupport* compositor_support =
565 WebKit::Platform::current()->compositorSupport();
566 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
568 // TODO(fsamuel): Guests don't currently support threaded compositing.
569 // This should go away with the new design of the browser plugin.
570 // The new design can be tracked at: http://crbug.com/134492.
571 bool is_guest = CommandLine::ForCurrentProcess()->HasSwitch(
572 switches::kGuestRenderer);
573 bool threaded = CommandLine::ForCurrentProcess()->HasSwitch(
574 switches::kEnableThreadedCompositing);
576 bool enable = threaded && !is_guest;
577 if (enable) {
578 compositor_thread_.reset(new CompositorThread(this));
579 AddFilter(compositor_thread_->GetMessageFilter());
580 compositor_support->initialize(compositor_thread_->GetWebThread());
581 } else {
582 compositor_support->initialize(NULL);
584 compositor_initialized_ = true;
586 MessageLoop* output_surface_loop = enable ?
587 compositor_thread_->message_loop() :
588 MessageLoop::current();
590 compositor_output_surface_filter_ = CompositorOutputSurface::CreateFilter(
591 output_surface_loop->message_loop_proxy());
592 AddFilter(compositor_output_surface_filter_.get());
594 WebScriptController::enableV8SingleThreadMode();
596 RenderThreadImpl::RegisterSchemes();
598 webkit_glue::EnableWebCoreLogChannels(
599 command_line.GetSwitchValueASCII(switches::kWebCoreLogChannels));
601 if (CommandLine::ForCurrentProcess()->HasSwitch(
602 switches::kDomAutomationController)) {
603 base::StringPiece extension = GetContentClient()->GetDataResource(
604 IDR_DOM_AUTOMATION_JS, ui::SCALE_FACTOR_NONE);
605 RegisterExtension(new v8::Extension(
606 "dom_automation.js", extension.data(), 0, NULL, extension.size()));
609 web_database_observer_impl_.reset(
610 new WebDatabaseObserverImpl(sync_message_filter()));
611 WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
613 WebRuntimeFeatures::enableSockets(
614 !command_line.HasSwitch(switches::kDisableWebSockets));
616 WebRuntimeFeatures::enableDatabase(
617 !command_line.HasSwitch(switches::kDisableDatabases));
619 WebRuntimeFeatures::enableDataTransferItems(
620 !command_line.HasSwitch(switches::kDisableDataTransferItems));
622 WebRuntimeFeatures::enableApplicationCache(
623 !command_line.HasSwitch(switches::kDisableApplicationCache));
625 WebRuntimeFeatures::enableNotifications(
626 !command_line.HasSwitch(switches::kDisableDesktopNotifications));
628 WebRuntimeFeatures::enableLocalStorage(
629 !command_line.HasSwitch(switches::kDisableLocalStorage));
630 WebRuntimeFeatures::enableSessionStorage(
631 !command_line.HasSwitch(switches::kDisableSessionStorage));
633 WebRuntimeFeatures::enableIndexedDatabase(true);
635 WebRuntimeFeatures::enableGeolocation(
636 !command_line.HasSwitch(switches::kDisableGeolocation));
638 WebKit::WebRuntimeFeatures::enableMediaSource(
639 !command_line.HasSwitch(switches::kDisableMediaSource));
641 WebRuntimeFeatures::enableMediaPlayer(
642 media::IsMediaLibraryInitialized());
644 WebKit::WebRuntimeFeatures::enableMediaStream(true);
645 WebKit::WebRuntimeFeatures::enablePeerConnection(true);
647 WebKit::WebRuntimeFeatures::enableFullScreenAPI(
648 !command_line.HasSwitch(switches::kDisableFullScreen));
650 WebKit::WebRuntimeFeatures::enableEncryptedMedia(
651 command_line.HasSwitch(switches::kEnableEncryptedMedia));
653 #if defined(OS_ANDROID)
654 WebRuntimeFeatures::enableWebAudio(
655 command_line.HasSwitch(switches::kEnableWebAudio) &&
656 media::IsMediaLibraryInitialized());
657 #else
658 WebRuntimeFeatures::enableWebAudio(
659 !command_line.HasSwitch(switches::kDisableWebAudio) &&
660 media::IsMediaLibraryInitialized());
661 #endif
663 WebRuntimeFeatures::enableDeviceMotion(
664 command_line.HasSwitch(switches::kEnableDeviceMotion));
666 WebRuntimeFeatures::enableDeviceOrientation(
667 !command_line.HasSwitch(switches::kDisableDeviceOrientation));
669 WebRuntimeFeatures::enableSpeechInput(
670 !command_line.HasSwitch(switches::kDisableSpeechInput));
672 WebRuntimeFeatures::enableScriptedSpeech(true);
674 WebRuntimeFeatures::enableFileSystem(
675 !command_line.HasSwitch(switches::kDisableFileSystem));
677 WebRuntimeFeatures::enableJavaScriptI18NAPI(
678 !command_line.HasSwitch(switches::kDisableJavaScriptI18NAPI));
680 WebRuntimeFeatures::enableGamepad(true);
682 WebRuntimeFeatures::enableQuota(true);
684 WebRuntimeFeatures::enableShadowDOM(true);
686 WebRuntimeFeatures::enableStyleScoped(
687 command_line.HasSwitch(switches::kEnableExperimentalWebKitFeatures));
689 WebRuntimeFeatures::enableCSSExclusions(
690 command_line.HasSwitch(switches::kEnableExperimentalWebKitFeatures));
692 WebRuntimeFeatures::enableExperimentalContentSecurityPolicyFeatures(
693 command_line.HasSwitch(switches::kEnableExperimentalWebKitFeatures));
695 WebRuntimeFeatures::enableWebIntents(
696 command_line.HasSwitch(switches::kWebIntentsInvocationEnabled));
698 WebRuntimeFeatures::enableCSSRegions(
699 command_line.HasSwitch(switches::kEnableExperimentalWebKitFeatures));
701 WebRuntimeFeatures::enableDialogElement(
702 command_line.HasSwitch(switches::kEnableExperimentalWebKitFeatures));
704 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
706 devtools_agent_message_filter_ = new DevToolsAgentFilter();
707 AddFilter(devtools_agent_message_filter_.get());
709 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
710 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
713 void RenderThreadImpl::RegisterSchemes() {
714 // swappedout: pages should not be accessible, and should also
715 // be treated as empty documents that can commit synchronously.
716 WebString swappedout_scheme(ASCIIToUTF16(chrome::kSwappedOutScheme));
717 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
718 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
721 void RenderThreadImpl::RecordUserMetrics(const std::string& action) {
722 Send(new ViewHostMsg_UserMetricsRecordAction(action));
725 scoped_ptr<base::SharedMemory>
726 RenderThreadImpl::HostAllocateSharedMemoryBuffer(uint32 size) {
727 //if (!size)
728 // return scoped_ptr<base::SharedMemory>();
730 //#if defined(OS_WIN)
731 // scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory);
732 // if (!shared_memory->CreateAnonymous(size))
733 // return scoped_ptr<base::SharedMemory>();
735 // return scoped_ptr<base::SharedMemory>(shared_memory.release());
736 //#else
737 base::SharedMemoryHandle handle;
738 bool success;
739 IPC::Message* message =
740 new ChildProcessHostMsg_SyncAllocateSharedMemory(size, &handle);
742 // Allow calling this from the compositor thread.
743 if (MessageLoop::current() == message_loop())
744 success = ChildThread::Send(message);
745 else
746 success = sync_message_filter()->Send(message);
748 if (!success)
749 return scoped_ptr<base::SharedMemory>();
751 if (!base::SharedMemory::IsHandleValid(handle))
752 return scoped_ptr<base::SharedMemory>();
754 return scoped_ptr<base::SharedMemory>(new base::SharedMemory(handle, false));
755 //#endif // defined(OS_WIN)
758 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
759 WebScriptController::registerExtension(extension);
762 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
763 idle_notification_delay_in_ms_ = initial_delay_ms;
764 idle_timer_.Stop();
765 idle_timer_.Start(FROM_HERE,
766 base::TimeDelta::FromMilliseconds(initial_delay_ms),
767 this, &RenderThreadImpl::IdleHandler);
770 void RenderThreadImpl::IdleHandler() {
771 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
772 GetContentClient()->renderer()->
773 RunIdleHandlerWhenWidgetsHidden();
774 if (run_in_foreground_tab) {
775 IdleHandlerInForegroundTab();
776 return;
779 base::allocator::ReleaseFreeMemory();
781 v8::V8::IdleNotification();
783 // Schedule next invocation.
784 // Dampen the delay using the algorithm (if delay is in seconds):
785 // delay = delay + 1 / (delay + 2)
786 // Using floor(delay) has a dampening effect such as:
787 // 1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
788 // If the delay is in milliseconds, the above formula is equivalent to:
789 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
790 // which is equivalent to
791 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
792 // Note that idle_notification_delay_in_ms_ would be reset to
793 // kInitialIdleHandlerDelayMs in RenderThreadImpl::WidgetHidden.
794 ScheduleIdleHandler(idle_notification_delay_in_ms_ +
795 1000000 / (idle_notification_delay_in_ms_ + 2000));
797 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
800 void RenderThreadImpl::IdleHandlerInForegroundTab() {
801 // Increase the delay in the same way as in IdleHandler,
802 // but make it periodic by reseting it once it is too big.
803 int64 new_delay_ms = idle_notification_delay_in_ms_ +
804 1000000 / (idle_notification_delay_in_ms_ + 2000);
805 if (new_delay_ms >= kLongIdleHandlerDelayMs)
806 new_delay_ms = kShortIdleHandlerDelayMs;
808 if (idle_notifications_to_skip_ > 0) {
809 idle_notifications_to_skip_--;
810 } else {
811 int cpu_usage = 0;
812 Send(new ViewHostMsg_GetCPUUsage(&cpu_usage));
813 // Idle notification hint roughly specifies the expected duration of the
814 // idle pause. We set it proportional to the idle timer delay.
815 int idle_hint = static_cast<int>(new_delay_ms / 10);
816 if (cpu_usage < kIdleCPUUsageThresholdInPercents) {
817 base::allocator::ReleaseFreeMemory();
818 if (v8::V8::IdleNotification(idle_hint)) {
819 // V8 finished collecting garbage.
820 new_delay_ms = kLongIdleHandlerDelayMs;
824 ScheduleIdleHandler(new_delay_ms);
827 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
828 return idle_notification_delay_in_ms_;
831 void RenderThreadImpl::SetIdleNotificationDelayInMs(
832 int64 idle_notification_delay_in_ms) {
833 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
836 void RenderThreadImpl::ToggleWebKitSharedTimer(bool suspend) {
837 if (suspend_webkit_shared_timer_) {
838 EnsureWebKitInitialized();
839 if (suspend) {
840 webkit_platform_support_->SuspendSharedTimer();
841 } else {
842 webkit_platform_support_->ResumeSharedTimer();
847 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
848 child_histogram_message_filter()->SendHistograms(sequence_number);
851 void RenderThreadImpl::PostponeIdleNotification() {
852 idle_notifications_to_skip_ = 2;
855 /* static */
856 void RenderThreadImpl::OnGpuVDAContextLoss() {
857 RenderThreadImpl* self = RenderThreadImpl::current();
858 DCHECK(self);
859 if (!self->gpu_vda_context3d_.get())
860 return;
861 if (self->compositor_thread()) {
862 self->compositor_thread()->GetWebThread()->message_loop()->DeleteSoon(
863 FROM_HERE, self->gpu_vda_context3d_.release());
864 } else {
865 self->gpu_vda_context3d_.reset();
869 WebGraphicsContext3DCommandBufferImpl*
870 RenderThreadImpl::GetGpuVDAContext3D() {
871 if (!gpu_vda_context3d_.get()) {
872 gpu_vda_context3d_.reset(
873 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
874 this, WebKit::WebGraphicsContext3D::Attributes(),
875 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D")));
876 if (gpu_vda_context3d_.get())
877 gpu_vda_context3d_->setContextLostCallback(context_lost_cb_.get());
879 return gpu_vda_context3d_.get();
882 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
883 if (!audio_renderer_mixer_manager_.get()) {
884 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
885 GetAudioOutputSampleRate(),
886 GetAudioOutputBufferSize()));
889 return audio_renderer_mixer_manager_.get();
892 #if defined(OS_WIN)
893 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
894 const string16& str) {
895 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
898 void RenderThreadImpl::PreCacheFont(const LOGFONT& log_font) {
899 Send(new ChildProcessHostMsg_PreCacheFont(log_font));
902 void RenderThreadImpl::ReleaseCachedFonts() {
903 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
906 #endif // OS_WIN
908 bool RenderThreadImpl::IsWebFrameValid(WebKit::WebFrame* web_frame) {
909 if (!web_frame)
910 return false; // We must be shutting down.
912 RenderViewImpl* render_view = RenderViewImpl::FromWebView(web_frame->view());
913 if (!render_view)
914 return false; // We must be shutting down.
916 return true;
919 bool RenderThreadImpl::IsMainThread() {
920 return !!current();
923 bool RenderThreadImpl::IsIOThread() {
924 return MessageLoop::current() == ChildProcess::current()->io_message_loop();
927 MessageLoop* RenderThreadImpl::GetMainLoop() {
928 return message_loop();
931 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
932 return ChildProcess::current()->io_message_loop_proxy();
935 base::WaitableEvent* RenderThreadImpl::GetShutDownEvent() {
936 return ChildProcess::current()->GetShutDownEvent();
939 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
940 uint32 size) {
941 return scoped_ptr<base::SharedMemory>(
942 HostAllocateSharedMemoryBuffer(size));
945 int32 RenderThreadImpl::CreateViewCommandBuffer(
946 int32 surface_id, const GPUCreateCommandBufferConfig& init_params) {
947 TRACE_EVENT1("gpu",
948 "RenderThreadImpl::CreateViewCommandBuffer",
949 "surface_id",
950 surface_id);
952 int32 route_id = MSG_ROUTING_NONE;
953 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
954 surface_id,
955 init_params,
956 &route_id);
958 // Allow calling this from the compositor thread.
959 if (MessageLoop::current() == message_loop())
960 ChildThread::Send(message);
961 else
962 sync_message_filter()->Send(message);
964 return route_id;
967 void RenderThreadImpl::CreateImage(
968 gfx::PluginWindowHandle window,
969 int32 image_id,
970 const CreateImageCallback& callback) {
971 NOTREACHED();
974 void RenderThreadImpl::DeleteImage(int32 image_id, int32 sync_point) {
975 NOTREACHED();
978 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
979 suspend_webkit_shared_timer_ = false;
982 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
983 notify_webkit_of_modal_loop_ = false;
986 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& host,
987 double zoom_level) {
988 RenderViewZoomer zoomer(host, zoom_level);
989 RenderView::ForEach(&zoomer);
992 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
993 ObserverListBase<RenderProcessObserver>::Iterator it(observers_);
994 RenderProcessObserver* observer;
995 while ((observer = it.GetNext()) != NULL) {
996 if (observer->OnControlMessageReceived(msg))
997 return true;
1000 // Some messages are handled by delegates.
1001 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1002 dom_storage_dispatcher_->OnMessageReceived(msg)) {
1003 return true;
1006 bool handled = true;
1007 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1008 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1009 OnSetZoomLevelForCurrentURL)
1010 // TODO(port): removed from render_messages_internal.h;
1011 // is there a new non-windows message I should add here?
1012 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1013 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1014 IPC_MESSAGE_HANDLER(ViewMsg_NetworkStateChanged, OnNetworkStateChanged)
1015 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1016 IPC_MESSAGE_UNHANDLED(handled = false)
1017 IPC_END_MESSAGE_MAP()
1018 return handled;
1021 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1022 EnsureWebKitInitialized();
1023 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1024 RenderViewImpl::Create(
1025 params.opener_route_id,
1026 params.renderer_preferences,
1027 params.web_preferences,
1028 new SharedRenderViewCounter(0),
1029 params.view_id,
1030 params.surface_id,
1031 params.session_storage_namespace_id,
1032 params.frame_name,
1033 false,
1034 params.swapped_out,
1035 params.next_page_id,
1036 params.screen_info,
1037 params.accessibility_mode);
1040 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1041 CauseForGpuLaunch cause_for_gpu_launch) {
1042 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1044 if (gpu_channel_.get()) {
1045 // Do nothing if we already have a GPU channel or are already
1046 // establishing one.
1047 if (gpu_channel_->state() == GpuChannelHost::kUnconnected ||
1048 gpu_channel_->state() == GpuChannelHost::kConnected)
1049 return GetGpuChannel();
1051 // Recreate the channel if it has been lost.
1052 gpu_channel_ = NULL;
1055 // Ask the browser for the channel name.
1056 int client_id = 0;
1057 IPC::ChannelHandle channel_handle;
1058 GPUInfo gpu_info;
1059 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1060 &client_id,
1061 &channel_handle,
1062 &gpu_info)) ||
1063 #if defined(OS_POSIX)
1064 channel_handle.socket.fd == -1 ||
1065 #endif
1066 channel_handle.name.empty()) {
1067 // Otherwise cancel the connection.
1068 gpu_channel_ = NULL;
1069 return NULL;
1072 gpu_channel_ = new GpuChannelHost(this, 0, client_id);
1073 gpu_channel_->set_gpu_info(gpu_info);
1074 GetContentClient()->SetGpuInfo(gpu_info);
1076 // Connect to the GPU process if a channel name was received.
1077 gpu_channel_->Connect(channel_handle);
1079 return GetGpuChannel();
1082 WebKit::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1083 WebKit::WebMediaStreamCenterClient* client) {
1084 #if defined(ENABLE_WEBRTC)
1085 if (!media_stream_center_)
1086 media_stream_center_ = new MediaStreamCenter(
1087 client, GetMediaStreamDependencyFactory());
1088 #endif
1089 return media_stream_center_;
1092 MediaStreamDependencyFactory*
1093 RenderThreadImpl::GetMediaStreamDependencyFactory() {
1094 #if defined(ENABLE_WEBRTC)
1095 if (!media_stream_factory_.get()) {
1096 media_stream_factory_.reset(new MediaStreamDependencyFactory(
1097 vc_manager_, p2p_socket_dispatcher_));
1099 #endif
1100 return media_stream_factory_.get();
1103 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1104 if (!gpu_channel_.get())
1105 return NULL;
1107 if (gpu_channel_->state() != GpuChannelHost::kConnected)
1108 return NULL;
1110 return gpu_channel_.get();
1113 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1114 EnsureWebKitInitialized();
1115 // The call below will cause a GetPlugins call with refresh=true, but at this
1116 // point we already know that the browser has refreshed its list, so disable
1117 // refresh temporarily to prevent each renderer process causing the list to be
1118 // regenerated.
1119 webkit_platform_support_->set_plugin_refresh_allowed(false);
1120 WebKit::resetPluginCache(reload_pages);
1121 webkit_platform_support_->set_plugin_refresh_allowed(true);
1123 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1126 void RenderThreadImpl::OnNetworkStateChanged(bool online) {
1127 EnsureWebKitInitialized();
1128 WebNetworkStateNotifier::setOnLine(online);
1131 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1132 GetContentClient()->SetActiveURL(data);
1133 CHECK(false);
1136 scoped_refptr<base::MessageLoopProxy>
1137 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1138 DCHECK(message_loop() == MessageLoop::current());
1139 if (!file_thread_.get()) {
1140 file_thread_.reset(new base::Thread("Renderer::FILE"));
1141 file_thread_->Start();
1143 return file_thread_->message_loop_proxy();
1146 } // namespace content