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/renderer_blink_platform_impl.h"
7 #include "base/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/lazy_instance.h"
10 #include "base/logging.h"
11 #include "base/memory/shared_memory.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/metrics/histogram.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "cc/blink/context_provider_web_context.h"
18 #include "content/child/database_util.h"
19 #include "content/child/file_info_util.h"
20 #include "content/child/fileapi/webfilesystem_impl.h"
21 #include "content/child/indexed_db/webidbfactory_impl.h"
22 #include "content/child/npapi/npobject_util.h"
23 #include "content/child/quota_dispatcher.h"
24 #include "content/child/quota_message_filter.h"
25 #include "content/child/simple_webmimeregistry_impl.h"
26 #include "content/child/thread_safe_sender.h"
27 #include "content/child/web_database_observer_impl.h"
28 #include "content/child/webblobregistry_impl.h"
29 #include "content/child/webfileutilities_impl.h"
30 #include "content/child/webmessageportchannel_impl.h"
31 #include "content/common/file_utilities_messages.h"
32 #include "content/common/gpu/client/context_provider_command_buffer.h"
33 #include "content/common/gpu/client/gpu_channel_host.h"
34 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
35 #include "content/common/gpu/gpu_process_launch_causes.h"
36 #include "content/common/mime_registry_messages.h"
37 #include "content/common/view_messages.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/service_registry.h"
40 #include "content/public/common/webplugininfo.h"
41 #include "content/public/renderer/content_renderer_client.h"
42 #include "content/renderer/battery_status/battery_status_dispatcher.h"
43 #include "content/renderer/device_sensors/device_light_event_pump.h"
44 #include "content/renderer/device_sensors/device_motion_event_pump.h"
45 #include "content/renderer/device_sensors/device_orientation_event_pump.h"
46 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
47 #include "content/renderer/gamepad_shared_memory_reader.h"
48 #include "content/renderer/media/audio_decoder.h"
49 #include "content/renderer/media/renderer_webaudiodevice_impl.h"
50 #include "content/renderer/media/renderer_webmidiaccessor_impl.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_clipboard_delegate.h"
53 #include "content/renderer/scheduler/renderer_scheduler.h"
54 #include "content/renderer/scheduler/web_scheduler_impl.h"
55 #include "content/renderer/scheduler/webthread_impl_for_scheduler.h"
56 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
57 #include "content/renderer/webclipboard_impl.h"
58 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
59 #include "content/renderer/webpublicsuffixlist_impl.h"
60 #include "gpu/config/gpu_info.h"
61 #include "ipc/ipc_sync_message_filter.h"
62 #include "media/audio/audio_output_device.h"
63 #include "media/base/audio_hardware_config.h"
64 #include "media/base/key_systems.h"
65 #include "media/blink/webcontentdecryptionmodule_impl.h"
66 #include "media/filters/stream_parser_factory.h"
67 #include "net/base/mime_util.h"
68 #include "net/base/net_util.h"
69 #include "storage/common/quota/quota_types.h"
70 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
71 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
72 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
73 #include "third_party/WebKit/public/platform/WebDeviceMotionListener.h"
74 #include "third_party/WebKit/public/platform/WebDeviceOrientationListener.h"
75 #include "third_party/WebKit/public/platform/WebFileInfo.h"
76 #include "third_party/WebKit/public/platform/WebGamepads.h"
77 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
78 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
79 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
80 #include "third_party/WebKit/public/platform/WebURL.h"
81 #include "third_party/WebKit/public/platform/WebVector.h"
82 #include "ui/gfx/color_profile.h"
85 #if defined(OS_ANDROID)
86 #include "content/renderer/android/synchronous_compositor_factory.h"
87 #include "content/renderer/media/android/audio_decoder_android.h"
88 #include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h"
91 #if defined(OS_MACOSX)
92 #include "content/common/mac/font_descriptor.h"
93 #include "content/common/mac/font_loader.h"
94 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
95 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
99 #include "base/file_descriptor_posix.h"
100 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
104 #include "base/synchronization/lock.h"
105 #include "content/common/child_process_sandbox_support_impl_linux.h"
106 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
107 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
108 #include "third_party/icu/source/common/unicode/utf16.h"
113 #include "content/common/child_process_messages.h"
114 #include "third_party/WebKit/public/platform/win/WebSandboxSupport.h"
117 #if defined(USE_AURA)
118 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
119 #elif !defined(OS_MACOSX)
120 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
121 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
124 #if defined(ENABLE_WEBRTC)
125 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
128 using blink::Platform
;
129 using blink::WebAudioDevice
;
130 using blink::WebBlobRegistry
;
131 using blink::WebDatabaseObserver
;
132 using blink::WebFileInfo
;
133 using blink::WebFileSystem
;
134 using blink::WebGamepad
;
135 using blink::WebGamepads
;
136 using blink::WebIDBFactory
;
137 using blink::WebMIDIAccessor
;
138 using blink::WebMediaStreamCenter
;
139 using blink::WebMediaStreamCenterClient
;
140 using blink::WebMimeRegistry
;
141 using blink::WebRTCPeerConnectionHandler
;
142 using blink::WebRTCPeerConnectionHandlerClient
;
143 using blink::WebStorageNamespace
;
144 using blink::WebString
;
146 using blink::WebVector
;
152 bool g_sandbox_enabled
= true;
153 double g_test_device_light_data
= -1;
154 base::LazyInstance
<blink::WebDeviceMotionData
>::Leaky
155 g_test_device_motion_data
= LAZY_INSTANCE_INITIALIZER
;
156 base::LazyInstance
<blink::WebDeviceOrientationData
>::Leaky
157 g_test_device_orientation_data
= LAZY_INSTANCE_INITIALIZER
;
158 // Set in startListening() when running layout tests, unset in stopListening(),
160 blink::WebBatteryStatusListener
* g_test_battery_status_listener
= nullptr;
164 //------------------------------------------------------------------------------
166 class RendererBlinkPlatformImpl::MimeRegistry
167 : public SimpleWebMimeRegistryImpl
{
169 virtual blink::WebMimeRegistry::SupportsType
supportsMediaMIMEType(
170 const blink::WebString
& mime_type
,
171 const blink::WebString
& codecs
,
172 const blink::WebString
& key_system
);
173 virtual bool supportsMediaSourceMIMEType(const blink::WebString
& mime_type
,
174 const blink::WebString
& codecs
);
175 virtual blink::WebString
mimeTypeForExtension(
176 const blink::WebString
& file_extension
);
177 virtual blink::WebString
mimeTypeFromFile(
178 const blink::WebString
& file_path
);
181 class RendererBlinkPlatformImpl::FileUtilities
: public WebFileUtilitiesImpl
{
183 explicit FileUtilities(ThreadSafeSender
* sender
)
184 : thread_safe_sender_(sender
) {}
185 virtual bool getFileInfo(const WebString
& path
, WebFileInfo
& result
);
187 bool SendSyncMessageFromAnyThread(IPC::SyncMessage
* msg
) const;
188 scoped_refptr
<ThreadSafeSender
> thread_safe_sender_
;
191 #if defined(OS_ANDROID)
192 // WebKit doesn't use WebSandboxSupport on android so we don't need to
193 // implement anything here.
194 class RendererBlinkPlatformImpl::SandboxSupport
{};
196 class RendererBlinkPlatformImpl::SandboxSupport
197 : public blink::WebSandboxSupport
{
199 virtual ~SandboxSupport() {}
202 virtual bool ensureFontLoaded(HFONT
);
203 #elif defined(OS_MACOSX)
204 virtual bool loadFont(
206 CGFontRef
* container
,
208 #elif defined(OS_POSIX)
209 virtual void getFallbackFontForCharacter(
210 blink::WebUChar32 character
,
211 const char* preferred_locale
,
212 blink::WebFallbackFont
* fallbackFont
);
213 virtual void getRenderStyleForStrike(
214 const char* family
, int sizeAndStyle
, blink::WebFontRenderStyle
* out
);
217 // WebKit likes to ask us for the correct font family to use for a set of
218 // unicode code points. It needs this information frequently so we cache it
220 base::Lock unicode_font_families_mutex_
;
221 std::map
<int32_t, blink::WebFallbackFont
> unicode_font_families_
;
224 #endif // defined(OS_ANDROID)
226 //------------------------------------------------------------------------------
228 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
229 RendererScheduler
* renderer_scheduler
)
230 : BlinkPlatformImpl(renderer_scheduler
->DefaultTaskRunner()),
231 web_scheduler_(new WebSchedulerImpl(renderer_scheduler
)),
232 main_thread_(new WebThreadImplForScheduler(renderer_scheduler
)),
233 clipboard_delegate_(new RendererClipboardDelegate
),
234 clipboard_(new WebClipboardImpl(clipboard_delegate_
.get())),
235 mime_registry_(new RendererBlinkPlatformImpl::MimeRegistry
),
236 sudden_termination_disables_(0),
237 plugin_refresh_allowed_(true),
238 default_task_runner_(renderer_scheduler
->DefaultTaskRunner()),
239 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl
) {
240 if (g_sandbox_enabled
&& sandboxEnabled()) {
241 sandbox_support_
.reset(new RendererBlinkPlatformImpl::SandboxSupport
);
243 DVLOG(1) << "Disabling sandbox support for testing.";
246 // ChildThread may not exist in some tests.
247 if (ChildThreadImpl::current()) {
248 sync_message_filter_
= ChildThreadImpl::current()->sync_message_filter();
249 thread_safe_sender_
= ChildThreadImpl::current()->thread_safe_sender();
250 quota_message_filter_
= ChildThreadImpl::current()->quota_message_filter();
251 blob_registry_
.reset(new WebBlobRegistryImpl(thread_safe_sender_
.get()));
252 web_idb_factory_
.reset(new WebIDBFactoryImpl(thread_safe_sender_
.get()));
253 web_database_observer_impl_
.reset(
254 new WebDatabaseObserverImpl(sync_message_filter_
.get()));
258 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
259 WebFileSystemImpl::DeleteThreadSpecificInstance();
262 //------------------------------------------------------------------------------
264 blink::WebScheduler
* RendererBlinkPlatformImpl::scheduler() {
265 return web_scheduler_
.get();
268 blink::WebThread
* RendererBlinkPlatformImpl::currentThread() {
269 if (main_thread_
->isCurrentThread())
270 return main_thread_
.get();
271 return BlinkPlatformImpl::currentThread();
274 blink::WebClipboard
* RendererBlinkPlatformImpl::clipboard() {
275 blink::WebClipboard
* clipboard
=
276 GetContentClient()->renderer()->OverrideWebClipboard();
279 return clipboard_
.get();
282 blink::WebMimeRegistry
* RendererBlinkPlatformImpl::mimeRegistry() {
283 return mime_registry_
.get();
286 blink::WebFileUtilities
* RendererBlinkPlatformImpl::fileUtilities() {
287 if (!file_utilities_
) {
288 file_utilities_
.reset(new FileUtilities(thread_safe_sender_
.get()));
289 file_utilities_
->set_sandbox_enabled(sandboxEnabled());
291 return file_utilities_
.get();
294 blink::WebSandboxSupport
* RendererBlinkPlatformImpl::sandboxSupport() {
295 #if defined(OS_ANDROID)
296 // WebKit doesn't use WebSandboxSupport on android.
299 return sandbox_support_
.get();
303 blink::WebCookieJar
* RendererBlinkPlatformImpl::cookieJar() {
304 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
308 blink::WebThemeEngine
* RendererBlinkPlatformImpl::themeEngine() {
309 blink::WebThemeEngine
* theme_engine
=
310 GetContentClient()->renderer()->OverrideThemeEngine();
313 return BlinkPlatformImpl::themeEngine();
316 bool RendererBlinkPlatformImpl::sandboxEnabled() {
317 // As explained in Platform.h, this function is used to decide
318 // whether to allow file system operations to come out of WebKit or not.
319 // Even if the sandbox is disabled, there's no reason why the code should
320 // act any differently...unless we're in single process mode. In which
321 // case, we have no other choice. Platform.h discourages using
322 // this switch unless absolutely necessary, so hopefully we won't end up
323 // with too many code paths being different in single-process mode.
324 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
325 switches::kSingleProcess
);
328 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
329 const char* canonical_url
,
331 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url
, length
);
334 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash
) {
335 return GetContentClient()->renderer()->IsLinkVisited(link_hash
);
338 void RendererBlinkPlatformImpl::createMessageChannel(
339 blink::WebMessagePortChannel
** channel1
,
340 blink::WebMessagePortChannel
** channel2
) {
341 WebMessagePortChannelImpl::CreatePair(
342 default_task_runner_
, channel1
, channel2
);
345 blink::WebPrescientNetworking
*
346 RendererBlinkPlatformImpl::prescientNetworking() {
347 return GetContentClient()->renderer()->GetPrescientNetworking();
350 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL
& url
,
354 // Let the browser know we generated cacheable metadata for this resource. The
355 // browser may cache it and return it on subsequent responses to speed
356 // the processing of this resource.
357 std::vector
<char> copy(data
, data
+ size
);
358 RenderThread::Get()->Send(new ViewHostMsg_DidGenerateCacheableMetadata(
359 url
, base::Time::FromInternalValue(response_time
), copy
));
362 WebString
RendererBlinkPlatformImpl::defaultLocale() {
363 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
366 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled
) {
368 // We should not get more enables than disables, but we want it to be a
369 // non-fatal error if it does happen.
370 DCHECK_GT(sudden_termination_disables_
, 0);
371 sudden_termination_disables_
= std::max(sudden_termination_disables_
- 1,
373 if (sudden_termination_disables_
!= 0)
376 sudden_termination_disables_
++;
377 if (sudden_termination_disables_
!= 1)
381 RenderThread
* thread
= RenderThread::Get();
382 if (thread
) // NULL in unittests.
383 thread
->Send(new ViewHostMsg_SuddenTerminationChanged(enabled
));
386 WebStorageNamespace
* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
387 return new WebStorageNamespaceImpl();
391 //------------------------------------------------------------------------------
393 WebIDBFactory
* RendererBlinkPlatformImpl::idbFactory() {
394 return web_idb_factory_
.get();
397 //------------------------------------------------------------------------------
399 WebFileSystem
* RendererBlinkPlatformImpl::fileSystem() {
400 return WebFileSystemImpl::ThreadSpecificInstance(default_task_runner_
);
403 //------------------------------------------------------------------------------
405 WebMimeRegistry::SupportsType
406 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
407 const WebString
& mime_type
,
408 const WebString
& codecs
,
409 const WebString
& key_system
) {
410 const std::string mime_type_ascii
= ToASCIIOrEmpty(mime_type
);
411 // Not supporting the container is a flat-out no.
412 if (!net::IsSupportedMediaMimeType(mime_type_ascii
))
413 return IsNotSupported
;
415 if (!key_system
.isEmpty()) {
416 // Check whether the key system is supported with the mime_type and codecs.
418 // Chromium only supports ASCII parameters.
419 if (!base::IsStringASCII(key_system
))
420 return IsNotSupported
;
422 std::string key_system_ascii
=
423 media::GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system
));
424 std::vector
<std::string
> strict_codecs
;
425 net::ParseCodecString(ToASCIIOrEmpty(codecs
), &strict_codecs
, true);
427 if (!media::PrefixedIsSupportedKeySystemWithMediaMimeType(
428 mime_type_ascii
, strict_codecs
, key_system_ascii
)) {
429 return IsNotSupported
;
432 // Continue processing the mime_type and codecs.
435 // Check list of strict codecs to see if it is supported.
436 if (net::IsStrictMediaMimeType(mime_type_ascii
)) {
437 // Check if the codecs are a perfect match.
438 std::vector
<std::string
> strict_codecs
;
439 net::ParseCodecString(ToASCIIOrEmpty(codecs
), &strict_codecs
, false);
440 return static_cast<WebMimeRegistry::SupportsType
> (
441 net::IsSupportedStrictMediaMimeType(mime_type_ascii
, strict_codecs
));
444 // If we don't recognize the codec, it's possible we support it.
445 std::vector
<std::string
> parsed_codecs
;
446 net::ParseCodecString(ToASCIIOrEmpty(codecs
), &parsed_codecs
, true);
447 if (!net::AreSupportedMediaCodecs(parsed_codecs
))
448 return MayBeSupported
;
450 // Otherwise we have a perfect match.
454 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
455 const blink::WebString
& mime_type
,
456 const WebString
& codecs
) {
457 const std::string mime_type_ascii
= ToASCIIOrEmpty(mime_type
);
458 std::vector
<std::string
> parsed_codec_ids
;
459 net::ParseCodecString(ToASCIIOrEmpty(codecs
), &parsed_codec_ids
, false);
460 if (mime_type_ascii
.empty())
462 return media::StreamParserFactory::IsTypeSupported(
463 mime_type_ascii
, parsed_codec_ids
);
466 WebString
RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
467 const WebString
& file_extension
) {
468 if (IsPluginProcess())
469 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension
);
471 // The sandbox restricts our access to the registry, so we need to proxy
472 // these calls over to the browser process.
473 std::string mime_type
;
474 RenderThread::Get()->Send(
475 new MimeRegistryMsg_GetMimeTypeFromExtension(
476 base::FilePath::FromUTF16Unsafe(file_extension
).value(), &mime_type
));
477 return base::ASCIIToUTF16(mime_type
);
480 WebString
RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
481 const WebString
& file_path
) {
482 if (IsPluginProcess())
483 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path
);
485 // The sandbox restricts our access to the registry, so we need to proxy
486 // these calls over to the browser process.
487 std::string mime_type
;
488 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
489 base::FilePath::FromUTF16Unsafe(file_path
),
491 return base::ASCIIToUTF16(mime_type
);
494 //------------------------------------------------------------------------------
496 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
497 const WebString
& path
,
498 WebFileInfo
& web_file_info
) {
499 base::File::Info file_info
;
500 base::File::Error status
= base::File::FILE_ERROR_MAX
;
501 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
502 base::FilePath::FromUTF16Unsafe(path
), &file_info
, &status
)) ||
503 status
!= base::File::FILE_OK
) {
506 FileInfoToWebFileInfo(file_info
, &web_file_info
);
507 web_file_info
.platformPath
= path
;
511 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
512 IPC::SyncMessage
* msg
) const {
513 base::TimeTicks begin
= base::TimeTicks::Now();
514 const bool success
= thread_safe_sender_
->Send(msg
);
515 base::TimeDelta delta
= base::TimeTicks::Now() - begin
;
516 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta
);
520 //------------------------------------------------------------------------------
524 bool RendererBlinkPlatformImpl::SandboxSupport::ensureFontLoaded(HFONT font
) {
526 GetObject(font
, sizeof(LOGFONT
), &logfont
);
527 RenderThread::Get()->PreCacheFont(logfont
);
531 #elif defined(OS_MACOSX)
533 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont
* src_font
,
536 uint32 font_data_size
;
537 FontDescriptor
src_font_descriptor(src_font
);
538 base::SharedMemoryHandle font_data
;
539 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
540 src_font_descriptor
, &font_data_size
, &font_data
, font_id
))) {
546 if (font_data_size
== 0 || font_data
== base::SharedMemory::NULLHandle() ||
548 LOG(ERROR
) << "Bad response from ViewHostMsg_LoadFont() for " <<
549 src_font_descriptor
.font_name
;
555 // TODO(jeremy): Need to call back into WebKit to make sure that the font
556 // isn't already activated, based on the font id. If it's already
557 // activated, don't reactivate it here - crbug.com/72727 .
559 return FontLoader::CGFontRefFromBuffer(font_data
, font_data_size
, out
);
562 #elif defined(OS_ANDROID)
564 // WebKit doesn't use WebSandboxSupport on android so we don't need to
565 // implement anything here. This is cleaner to support than excluding the
566 // whole class for android.
568 #elif defined(OS_POSIX)
570 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
571 blink::WebUChar32 character
,
572 const char* preferred_locale
,
573 blink::WebFallbackFont
* fallbackFont
) {
574 base::AutoLock
lock(unicode_font_families_mutex_
);
575 const std::map
<int32_t, blink::WebFallbackFont
>::const_iterator iter
=
576 unicode_font_families_
.find(character
);
577 if (iter
!= unicode_font_families_
.end()) {
578 fallbackFont
->name
= iter
->second
.name
;
579 fallbackFont
->filename
= iter
->second
.filename
;
580 fallbackFont
->fontconfigInterfaceId
= iter
->second
.fontconfigInterfaceId
;
581 fallbackFont
->ttcIndex
= iter
->second
.ttcIndex
;
582 fallbackFont
->isBold
= iter
->second
.isBold
;
583 fallbackFont
->isItalic
= iter
->second
.isItalic
;
587 GetFallbackFontForCharacter(character
, preferred_locale
, fallbackFont
);
588 unicode_font_families_
.insert(std::make_pair(character
, *fallbackFont
));
591 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
594 blink::WebFontRenderStyle
* out
) {
595 GetRenderStyleForStrike(family
, sizeAndStyle
, out
);
600 //------------------------------------------------------------------------------
602 Platform::FileHandle
RendererBlinkPlatformImpl::databaseOpenFile(
603 const WebString
& vfs_file_name
,
605 return DatabaseUtil::DatabaseOpenFile(
606 vfs_file_name
, desired_flags
, sync_message_filter_
.get());
609 int RendererBlinkPlatformImpl::databaseDeleteFile(
610 const WebString
& vfs_file_name
,
612 return DatabaseUtil::DatabaseDeleteFile(
613 vfs_file_name
, sync_dir
, sync_message_filter_
.get());
616 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
617 const WebString
& vfs_file_name
) {
618 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name
,
619 sync_message_filter_
.get());
622 long long RendererBlinkPlatformImpl::databaseGetFileSize(
623 const WebString
& vfs_file_name
) {
624 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name
,
625 sync_message_filter_
.get());
628 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
629 const WebString
& origin_identifier
) {
630 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier
,
631 sync_message_filter_
.get());
634 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
635 RenderThreadImpl
* thread
= RenderThreadImpl::current();
636 GpuChannelHost
* host
= thread
->EstablishGpuChannelSync(
637 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D
);
641 return host
->gpu_info().SupportsAccelerated2dCanvas();
644 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
645 RenderThreadImpl
* thread
= RenderThreadImpl::current();
646 // thread can be NULL in tests.
647 return thread
&& thread
->compositor_message_loop_proxy().get();
650 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
651 RenderThreadImpl
* thread
= RenderThreadImpl::current();
652 return thread
->GetAudioHardwareConfig()->GetOutputSampleRate();
655 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
656 RenderThreadImpl
* thread
= RenderThreadImpl::current();
657 return thread
->GetAudioHardwareConfig()->GetOutputBufferSize();
660 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
661 RenderThreadImpl
* thread
= RenderThreadImpl::current();
662 return thread
->GetAudioHardwareConfig()->GetOutputChannels();
665 WebDatabaseObserver
* RendererBlinkPlatformImpl::databaseObserver() {
666 return web_database_observer_impl_
.get();
669 WebAudioDevice
* RendererBlinkPlatformImpl::createAudioDevice(
671 unsigned input_channels
,
674 WebAudioDevice::RenderCallback
* callback
,
675 const blink::WebString
& input_device_id
) {
676 // Use a mock for testing.
677 blink::WebAudioDevice
* mock_device
=
678 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate
);
682 // The |channels| does not exactly identify the channel layout of the
683 // device. The switch statement below assigns a best guess to the channel
684 // layout based on number of channels.
685 // TODO(crogers): WebKit should give the channel layout instead of the hard
687 media::ChannelLayout layout
= media::CHANNEL_LAYOUT_UNSUPPORTED
;
690 layout
= media::CHANNEL_LAYOUT_MONO
;
693 layout
= media::CHANNEL_LAYOUT_STEREO
;
696 layout
= media::CHANNEL_LAYOUT_2_1
;
699 layout
= media::CHANNEL_LAYOUT_4_0
;
702 layout
= media::CHANNEL_LAYOUT_5_0
;
705 layout
= media::CHANNEL_LAYOUT_5_1
;
708 layout
= media::CHANNEL_LAYOUT_7_0
;
711 layout
= media::CHANNEL_LAYOUT_7_1
;
714 layout
= media::CHANNEL_LAYOUT_STEREO
;
718 if (input_device_id
.isNull() ||
719 !base::StringToInt(base::UTF16ToUTF8(input_device_id
), &session_id
)) {
720 if (input_channels
> 0)
721 DLOG(WARNING
) << "createAudioDevice(): request for audio input ignored";
726 media::AudioParameters
params(
727 media::AudioParameters::AUDIO_PCM_LOW_LATENCY
,
728 layout
, static_cast<int>(sample_rate
), 16, buffer_size
,
729 media::AudioParameters::NO_EFFECTS
);
731 return new RendererWebAudioDeviceImpl(params
, callback
, session_id
);
734 #if defined(OS_ANDROID)
735 bool RendererBlinkPlatformImpl::loadAudioResource(
736 blink::WebAudioBus
* destination_bus
,
737 const char* audio_file_data
,
739 return DecodeAudioFileData(destination_bus
,
742 thread_safe_sender_
);
745 bool RendererBlinkPlatformImpl::loadAudioResource(
746 blink::WebAudioBus
* destination_bus
,
747 const char* audio_file_data
,
749 return DecodeAudioFileData(
750 destination_bus
, audio_file_data
, data_size
);
752 #endif // defined(OS_ANDROID)
754 //------------------------------------------------------------------------------
756 blink::WebMIDIAccessor
* RendererBlinkPlatformImpl::createMIDIAccessor(
757 blink::WebMIDIAccessorClient
* client
) {
758 blink::WebMIDIAccessor
* accessor
=
759 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client
);
763 return new RendererWebMIDIAccessorImpl(client
);
766 void RendererBlinkPlatformImpl::getPluginList(
768 blink::WebPluginListBuilder
* builder
) {
769 #if defined(ENABLE_PLUGINS)
770 std::vector
<WebPluginInfo
> plugins
;
771 if (!plugin_refresh_allowed_
)
773 RenderThread::Get()->Send(
774 new ViewHostMsg_GetPlugins(refresh
, &plugins
));
775 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
776 const WebPluginInfo
& plugin
= plugins
[i
];
779 plugin
.name
, plugin
.desc
,
780 plugin
.path
.BaseName().AsUTF16Unsafe());
782 for (size_t j
= 0; j
< plugin
.mime_types
.size(); ++j
) {
783 const WebPluginMimeType
& mime_type
= plugin
.mime_types
[j
];
785 builder
->addMediaTypeToLastPlugin(
786 WebString::fromUTF8(mime_type
.mime_type
), mime_type
.description
);
788 for (size_t k
= 0; k
< mime_type
.file_extensions
.size(); ++k
) {
789 builder
->addFileExtensionToLastMediaType(
790 WebString::fromUTF8(mime_type
.file_extensions
[k
]));
797 //------------------------------------------------------------------------------
799 blink::WebPublicSuffixList
* RendererBlinkPlatformImpl::publicSuffixList() {
800 return &public_suffix_list_
;
803 //------------------------------------------------------------------------------
805 blink::WebString
RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
806 unsigned key_size_index
,
807 const blink::WebString
& challenge
,
808 const blink::WebURL
& url
) {
809 std::string signed_public_key
;
810 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
811 static_cast<uint32
>(key_size_index
),
814 &signed_public_key
));
815 return WebString::fromUTF8(signed_public_key
);
818 //------------------------------------------------------------------------------
820 void RendererBlinkPlatformImpl::screenColorProfile(
821 WebVector
<char>* to_profile
) {
823 // On Windows screen color profile is only available in the browser.
824 std::vector
<char> profile
;
825 // This Send() can be called from any impl-side thread. Use a thread
826 // safe send to avoid crashing trying to access RenderThread::Get(),
827 // which is not accessible from arbitrary threads.
828 thread_safe_sender_
->Send(
829 new ViewHostMsg_GetMonitorColorProfile(&profile
));
830 *to_profile
= profile
;
832 // On other platforms, the primary monitor color profile can be read
834 gfx::ColorProfile profile
;
835 *to_profile
= profile
.profile();
839 //------------------------------------------------------------------------------
841 blink::WebScrollbarBehavior
* RendererBlinkPlatformImpl::scrollbarBehavior() {
842 return web_scrollbar_behavior_
.get();
845 //------------------------------------------------------------------------------
847 WebBlobRegistry
* RendererBlinkPlatformImpl::blobRegistry() {
848 // blob_registry_ can be NULL when running some tests.
849 return blob_registry_
.get();
852 //------------------------------------------------------------------------------
854 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads
& gamepads
) {
855 PlatformEventObserverBase
* observer
=
856 platform_event_observers_
.Lookup(blink::WebPlatformEventGamepad
);
859 static_cast<RendererGamepadProvider
*>(observer
)->SampleGamepads(gamepads
);
862 //------------------------------------------------------------------------------
864 WebRTCPeerConnectionHandler
*
865 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
866 WebRTCPeerConnectionHandlerClient
* client
) {
867 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
868 DCHECK(render_thread
);
872 #if defined(ENABLE_WEBRTC)
873 WebRTCPeerConnectionHandler
* peer_connection_handler
=
874 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
876 if (peer_connection_handler
)
877 return peer_connection_handler
;
879 PeerConnectionDependencyFactory
* rtc_dependency_factory
=
880 render_thread
->GetPeerConnectionDependencyFactory();
881 return rtc_dependency_factory
->CreateRTCPeerConnectionHandler(client
);
884 #endif // defined(ENABLE_WEBRTC)
887 //------------------------------------------------------------------------------
889 WebMediaStreamCenter
* RendererBlinkPlatformImpl::createMediaStreamCenter(
890 WebMediaStreamCenterClient
* client
) {
891 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
892 DCHECK(render_thread
);
895 return render_thread
->CreateMediaStreamCenter(client
);
899 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable
) {
900 bool was_enabled
= g_sandbox_enabled
;
901 g_sandbox_enabled
= enable
;
905 //------------------------------------------------------------------------------
907 blink::WebSpeechSynthesizer
* RendererBlinkPlatformImpl::createSpeechSynthesizer(
908 blink::WebSpeechSynthesizerClient
* client
) {
909 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client
);
912 //------------------------------------------------------------------------------
914 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
915 size_t* private_bytes
,
916 size_t* shared_bytes
) {
917 content::RenderThread::Get()->Send(
918 new ViewHostMsg_GetProcessMemorySizes(private_bytes
, shared_bytes
));
922 //------------------------------------------------------------------------------
924 blink::WebGraphicsContext3D
*
925 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
926 const blink::WebGraphicsContext3D::Attributes
& attributes
) {
927 return createOffscreenGraphicsContext3D(attributes
, NULL
);
930 blink::WebGraphicsContext3D
*
931 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
932 const blink::WebGraphicsContext3D::Attributes
& attributes
,
933 blink::WebGraphicsContext3D
* share_context
) {
934 return createOffscreenGraphicsContext3D(attributes
, share_context
, NULL
);
937 blink::WebGraphicsContext3D
*
938 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
939 const blink::WebGraphicsContext3D::Attributes
& attributes
,
940 blink::WebGraphicsContext3D
* share_context
,
941 blink::WebGLInfo
* gl_info
) {
942 if (!RenderThreadImpl::current())
945 #if defined(OS_ANDROID)
946 if (SynchronousCompositorFactory
* factory
=
947 SynchronousCompositorFactory::GetInstance()) {
948 scoped_ptr
<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl
>
950 factory
->CreateOffscreenGraphicsContext3D(attributes
));
951 if (!in_process_context
||
952 !in_process_context
->InitializeOnCurrentThread())
954 return in_process_context
.release();
958 scoped_refptr
<GpuChannelHost
> gpu_channel_host(
959 RenderThreadImpl::current()->EstablishGpuChannelSync(
960 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
962 if (gpu_channel_host
.get() && gl_info
) {
963 const gpu::GPUInfo
& gpu_info
= gpu_channel_host
->gpu_info();
964 switch (gpu_info
.context_info_state
) {
965 case gpu::kCollectInfoSuccess
:
966 case gpu::kCollectInfoNonFatalFailure
:
967 gl_info
->vendorInfo
.assign(
968 blink::WebString::fromUTF8(gpu_info
.gl_vendor
));
969 gl_info
->rendererInfo
.assign(
970 blink::WebString::fromUTF8(gpu_info
.gl_renderer
));
971 gl_info
->driverVersion
.assign(
972 blink::WebString::fromUTF8(gpu_info
.driver_version
));
973 gl_info
->vendorId
= gpu_info
.gpu
.vendor_id
;
974 gl_info
->deviceId
= gpu_info
.gpu
.device_id
;
976 case gpu::kCollectInfoFatalFailure
:
977 case gpu::kCollectInfoNone
:
978 gl_info
->contextInfoCollectionFailure
.assign(blink::WebString::fromUTF8(
979 "GPUInfoCollectionFailure: GPU initialization Failed. GPU "
980 "Info not Collected."));
987 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits
;
988 bool lose_context_when_out_of_memory
= false;
989 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
> context(
990 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
991 gpu_channel_host
.get(),
993 lose_context_when_out_of_memory
,
994 GURL(attributes
.topDocumentURL
),
996 static_cast<WebGraphicsContext3DCommandBufferImpl
*>(share_context
)));
998 // Most likely the GPU process exited and the attempt to reconnect to it
999 // failed. Need to try to restore the context again later.
1000 if (!context
|| !context
->InitializeOnCurrentThread())
1002 return context
.release();
1005 //------------------------------------------------------------------------------
1007 blink::WebGraphicsContext3DProvider
*
1008 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
1009 scoped_refptr
<cc_blink::ContextProviderWebContext
> provider
=
1010 RenderThreadImpl::current()->SharedMainThreadContextProvider();
1011 if (!provider
.get())
1013 return new WebGraphicsContext3DProviderImpl(provider
);
1016 //------------------------------------------------------------------------------
1018 blink::WebCompositorSupport
* RendererBlinkPlatformImpl::compositorSupport() {
1019 return &compositor_support_
;
1022 //------------------------------------------------------------------------------
1024 blink::WebString
RendererBlinkPlatformImpl::convertIDNToUnicode(
1025 const blink::WebString
& host
,
1026 const blink::WebString
& languages
) {
1027 return net::IDNToUnicode(host
.utf8(), languages
.utf8());
1030 //------------------------------------------------------------------------------
1033 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data
) {
1034 g_test_device_light_data
= data
;
1037 //------------------------------------------------------------------------------
1040 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1041 const blink::WebDeviceMotionData
& data
) {
1042 g_test_device_motion_data
.Get() = data
;
1045 //------------------------------------------------------------------------------
1048 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1049 const blink::WebDeviceOrientationData
& data
) {
1050 g_test_device_orientation_data
.Get() = data
;
1053 //------------------------------------------------------------------------------
1055 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds
) {
1056 GetConnectedVibrationManagerService()->Vibrate(
1057 base::checked_cast
<int64
>(milliseconds
));
1058 vibration_manager_
.reset();
1061 void RendererBlinkPlatformImpl::cancelVibration() {
1062 GetConnectedVibrationManagerService()->Cancel();
1063 vibration_manager_
.reset();
1066 device::VibrationManagerPtr
&
1067 RendererBlinkPlatformImpl::GetConnectedVibrationManagerService() {
1068 if (!vibration_manager_
) {
1069 RenderThread::Get()->GetServiceRegistry()
1070 ->ConnectToRemoteService(&vibration_manager_
);
1072 return vibration_manager_
;
1075 //------------------------------------------------------------------------------
1078 PlatformEventObserverBase
*
1079 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1080 blink::WebPlatformEventType type
) {
1081 RenderThread
* thread
= RenderThreadImpl::current();
1083 // When running layout tests, those observers should not listen to the actual
1084 // hardware changes. In order to make that happen, they will receive a null
1086 if (thread
&& RenderThreadImpl::current()->layout_test_mode())
1090 case blink::WebPlatformEventDeviceMotion
:
1091 return new DeviceMotionEventPump(thread
);
1092 case blink::WebPlatformEventDeviceOrientation
:
1093 return new DeviceOrientationEventPump(thread
);
1094 case blink::WebPlatformEventDeviceLight
:
1095 return new DeviceLightEventPump(thread
);
1096 case blink::WebPlatformEventGamepad
:
1097 return new GamepadSharedMemoryReader(thread
);
1098 case blink::WebPlatformEventScreenOrientation
:
1099 return new ScreenOrientationObserver();
1101 // A default statement is required to prevent compilation errors when
1102 // Blink adds a new type.
1103 DVLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1110 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1111 blink::WebPlatformEventType type
,
1112 scoped_ptr
<PlatformEventObserverBase
> observer
) {
1113 DCHECK(type
!= blink::WebPlatformEventBattery
);
1115 if (platform_event_observers_
.Lookup(type
))
1116 platform_event_observers_
.Remove(type
);
1117 platform_event_observers_
.AddWithID(observer
.release(), type
);
1120 void RendererBlinkPlatformImpl::startListening(
1121 blink::WebPlatformEventType type
,
1122 blink::WebPlatformEventListener
* listener
) {
1123 if (type
== blink::WebPlatformEventBattery
) {
1124 if (RenderThreadImpl::current() &&
1125 RenderThreadImpl::current()->layout_test_mode()) {
1126 g_test_battery_status_listener
=
1127 static_cast<blink::WebBatteryStatusListener
*>(listener
);
1129 battery_status_dispatcher_
.reset(new BatteryStatusDispatcher(
1130 static_cast<blink::WebBatteryStatusListener
*>(listener
)));
1135 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1137 observer
= CreatePlatformEventObserverFromType(type
);
1140 platform_event_observers_
.AddWithID(observer
, static_cast<int32
>(type
));
1142 observer
->Start(listener
);
1144 // Device events (motion, orientation and light) expect to get an event fired
1145 // as soon as a listener is registered if a fake data was passed before.
1146 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1147 // using this broken pattern.
1148 if (RenderThreadImpl::current() &&
1149 RenderThreadImpl::current()->layout_test_mode() &&
1150 (type
== blink::WebPlatformEventDeviceMotion
||
1151 type
== blink::WebPlatformEventDeviceOrientation
||
1152 type
== blink::WebPlatformEventDeviceLight
)) {
1153 SendFakeDeviceEventDataForTesting(type
);
1157 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1158 blink::WebPlatformEventType type
) {
1159 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1165 case blink::WebPlatformEventDeviceMotion
:
1166 if (!(g_test_device_motion_data
== 0))
1167 data
= &g_test_device_motion_data
.Get();
1169 case blink::WebPlatformEventDeviceOrientation
:
1170 if (!(g_test_device_orientation_data
== 0))
1171 data
= &g_test_device_orientation_data
.Get();
1173 case blink::WebPlatformEventDeviceLight
:
1174 if (g_test_device_light_data
>= 0)
1175 data
= &g_test_device_light_data
;
1185 base::MessageLoopProxy::current()->PostTask(
1187 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting
,
1188 base::Unretained(observer
), data
));
1191 void RendererBlinkPlatformImpl::stopListening(
1192 blink::WebPlatformEventType type
) {
1193 if (type
== blink::WebPlatformEventBattery
) {
1194 g_test_battery_status_listener
= nullptr;
1195 battery_status_dispatcher_
.reset();
1199 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1205 //------------------------------------------------------------------------------
1207 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1208 const blink::WebURL
& storage_partition
,
1209 blink::WebStorageQuotaType type
,
1210 blink::WebStorageQuotaCallbacks callbacks
) {
1211 if (!thread_safe_sender_
.get() || !quota_message_filter_
.get())
1213 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_
.get(),
1214 quota_message_filter_
.get())
1215 ->QueryStorageUsageAndQuota(
1217 static_cast<storage::StorageType
>(type
),
1218 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
1221 //------------------------------------------------------------------------------
1223 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1224 const blink::WebBatteryStatus
& status
) {
1225 if (!g_test_battery_status_listener
)
1227 g_test_battery_status_listener
->updateBatteryStatus(status
);
1230 } // namespace content