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/location.h"
11 #include "base/logging.h"
12 #include "base/memory/shared_memory.h"
13 #include "base/metrics/histogram.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "build/build_config.h"
20 #include "cc/blink/context_provider_web_context.h"
21 #include "components/scheduler/child/web_scheduler_impl.h"
22 #include "components/scheduler/renderer/renderer_scheduler.h"
23 #include "components/scheduler/renderer/webthread_impl_for_renderer_scheduler.h"
24 #include "components/url_formatter/url_formatter.h"
25 #include "content/child/database_util.h"
26 #include "content/child/file_info_util.h"
27 #include "content/child/fileapi/webfilesystem_impl.h"
28 #include "content/child/indexed_db/webidbfactory_impl.h"
29 #include "content/child/npapi/npobject_util.h"
30 #include "content/child/quota_dispatcher.h"
31 #include "content/child/quota_message_filter.h"
32 #include "content/child/simple_webmimeregistry_impl.h"
33 #include "content/child/thread_safe_sender.h"
34 #include "content/child/web_database_observer_impl.h"
35 #include "content/child/webblobregistry_impl.h"
36 #include "content/child/webfileutilities_impl.h"
37 #include "content/child/webmessageportchannel_impl.h"
38 #include "content/common/file_utilities_messages.h"
39 #include "content/common/frame_messages.h"
40 #include "content/common/gpu/client/context_provider_command_buffer.h"
41 #include "content/common/gpu/client/gpu_channel_host.h"
42 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
43 #include "content/common/gpu/gpu_process_launch_causes.h"
44 #include "content/common/mime_registry_messages.h"
45 #include "content/common/view_messages.h"
46 #include "content/public/common/content_switches.h"
47 #include "content/public/common/service_registry.h"
48 #include "content/public/common/webplugininfo.h"
49 #include "content/public/renderer/content_renderer_client.h"
50 #include "content/renderer/battery_status/battery_status_dispatcher.h"
51 #include "content/renderer/cache_storage/webserviceworkercachestorage_impl.h"
52 #include "content/renderer/device_sensors/device_light_event_pump.h"
53 #include "content/renderer/device_sensors/device_motion_event_pump.h"
54 #include "content/renderer/device_sensors/device_orientation_event_pump.h"
55 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
56 #include "content/renderer/gamepad_shared_memory_reader.h"
57 #include "content/renderer/media/audio_decoder.h"
58 #include "content/renderer/media/media_recorder_handler.h"
59 #include "content/renderer/media/renderer_webaudiodevice_impl.h"
60 #include "content/renderer/media/renderer_webmidiaccessor_impl.h"
61 #include "content/renderer/render_thread_impl.h"
62 #include "content/renderer/renderer_clipboard_delegate.h"
63 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
64 #include "content/renderer/webclipboard_impl.h"
65 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
66 #include "content/renderer/webpublicsuffixlist_impl.h"
67 #include "gpu/config/gpu_info.h"
68 #include "ipc/ipc_sync_message_filter.h"
69 #include "media/audio/audio_output_device.h"
70 #include "media/base/audio_hardware_config.h"
71 #include "media/base/key_systems.h"
72 #include "media/base/mime_util.h"
73 #include "media/blink/webcontentdecryptionmodule_impl.h"
74 #include "media/filters/stream_parser_factory.h"
75 #include "storage/common/database/database_identifier.h"
76 #include "storage/common/quota/quota_types.h"
77 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
78 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
79 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
80 #include "third_party/WebKit/public/platform/WebFileInfo.h"
81 #include "third_party/WebKit/public/platform/WebGamepads.h"
82 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
83 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
84 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
85 #include "third_party/WebKit/public/platform/WebURL.h"
86 #include "third_party/WebKit/public/platform/WebVector.h"
87 #include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionListener.h"
88 #include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationListener.h"
89 #include "ui/gfx/color_profile.h"
92 #if defined(OS_ANDROID)
93 #include "content/renderer/android/synchronous_compositor_factory.h"
94 #include "content/renderer/media/android/audio_decoder_android.h"
95 #include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h"
98 #if defined(OS_MACOSX)
99 #include "content/common/mac/font_descriptor.h"
100 #include "content/common/mac/font_loader.h"
101 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
102 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
105 #if defined(OS_POSIX)
106 #include "base/file_descriptor_posix.h"
107 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
111 #include "base/synchronization/lock.h"
112 #include "content/common/child_process_sandbox_support_impl_linux.h"
113 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
114 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
115 #include "third_party/icu/source/common/unicode/utf16.h"
120 #include "content/common/child_process_messages.h"
123 #if defined(USE_AURA)
124 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
125 #elif !defined(OS_MACOSX)
126 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
127 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
130 #if defined(ENABLE_WEBRTC)
131 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
134 using blink::Platform
;
135 using blink::WebAudioDevice
;
136 using blink::WebBlobRegistry
;
137 using blink::WebDatabaseObserver
;
138 using blink::WebFileInfo
;
139 using blink::WebFileSystem
;
140 using blink::WebGamepad
;
141 using blink::WebGamepads
;
142 using blink::WebIDBFactory
;
143 using blink::WebMIDIAccessor
;
144 using blink::WebMediaRecorderHandler
;
145 using blink::WebMediaStreamCenter
;
146 using blink::WebMediaStreamCenterClient
;
147 using blink::WebMimeRegistry
;
148 using blink::WebRTCPeerConnectionHandler
;
149 using blink::WebRTCPeerConnectionHandlerClient
;
150 using blink::WebStorageNamespace
;
151 using blink::WebString
;
153 using blink::WebVector
;
159 bool g_sandbox_enabled
= true;
160 double g_test_device_light_data
= -1;
161 base::LazyInstance
<blink::WebDeviceMotionData
>::Leaky
162 g_test_device_motion_data
= LAZY_INSTANCE_INITIALIZER
;
163 base::LazyInstance
<blink::WebDeviceOrientationData
>::Leaky
164 g_test_device_orientation_data
= LAZY_INSTANCE_INITIALIZER
;
165 // Set in startListening() when running layout tests, unset in stopListening(),
167 blink::WebBatteryStatusListener
* g_test_battery_status_listener
= nullptr;
171 //------------------------------------------------------------------------------
173 class RendererBlinkPlatformImpl::MimeRegistry
174 : public SimpleWebMimeRegistryImpl
{
176 virtual blink::WebMimeRegistry::SupportsType
supportsMediaMIMEType(
177 const blink::WebString
& mime_type
,
178 const blink::WebString
& codecs
,
179 const blink::WebString
& key_system
);
180 virtual bool supportsMediaSourceMIMEType(const blink::WebString
& mime_type
,
181 const blink::WebString
& codecs
);
182 virtual blink::WebString
mimeTypeForExtension(
183 const blink::WebString
& file_extension
);
184 virtual blink::WebString
mimeTypeFromFile(
185 const blink::WebString
& file_path
);
188 class RendererBlinkPlatformImpl::FileUtilities
: public WebFileUtilitiesImpl
{
190 explicit FileUtilities(ThreadSafeSender
* sender
)
191 : thread_safe_sender_(sender
) {}
192 virtual bool getFileInfo(const WebString
& path
, WebFileInfo
& result
);
194 bool SendSyncMessageFromAnyThread(IPC::SyncMessage
* msg
) const;
195 scoped_refptr
<ThreadSafeSender
> thread_safe_sender_
;
198 #if !defined(OS_ANDROID) && !defined(OS_WIN)
199 class RendererBlinkPlatformImpl::SandboxSupport
200 : public blink::WebSandboxSupport
{
202 virtual ~SandboxSupport() {}
204 #if defined(OS_MACOSX)
205 virtual bool loadFont(
207 CGFontRef
* container
,
209 #elif defined(OS_POSIX)
210 virtual void getFallbackFontForCharacter(
211 blink::WebUChar32 character
,
212 const char* preferred_locale
,
213 blink::WebFallbackFont
* fallbackFont
);
214 virtual void getRenderStyleForStrike(
215 const char* family
, int sizeAndStyle
, blink::WebFontRenderStyle
* out
);
218 // WebKit likes to ask us for the correct font family to use for a set of
219 // unicode code points. It needs this information frequently so we cache it
221 base::Lock unicode_font_families_mutex_
;
222 std::map
<int32_t, blink::WebFallbackFont
> unicode_font_families_
;
225 #endif // !defined(OS_ANDROID) && !defined(OS_WIN)
227 //------------------------------------------------------------------------------
229 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
230 scheduler::RendererScheduler
* renderer_scheduler
)
231 : BlinkPlatformImpl(renderer_scheduler
->DefaultTaskRunner()),
233 new scheduler::WebThreadImplForRendererScheduler(renderer_scheduler
)),
234 clipboard_delegate_(new RendererClipboardDelegate
),
235 clipboard_(new WebClipboardImpl(clipboard_delegate_
.get())),
236 mime_registry_(new RendererBlinkPlatformImpl::MimeRegistry
),
237 sudden_termination_disables_(0),
238 plugin_refresh_allowed_(true),
239 default_task_runner_(renderer_scheduler
->DefaultTaskRunner()),
240 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl
) {
241 #if !defined(OS_ANDROID) && !defined(OS_WIN)
242 if (g_sandbox_enabled
&& sandboxEnabled()) {
243 sandbox_support_
.reset(new RendererBlinkPlatformImpl::SandboxSupport
);
245 DVLOG(1) << "Disabling sandbox support for testing.";
249 // ChildThread may not exist in some tests.
250 if (ChildThreadImpl::current()) {
251 sync_message_filter_
= ChildThreadImpl::current()->sync_message_filter();
252 thread_safe_sender_
= ChildThreadImpl::current()->thread_safe_sender();
253 quota_message_filter_
= ChildThreadImpl::current()->quota_message_filter();
254 blob_registry_
.reset(new WebBlobRegistryImpl(thread_safe_sender_
.get()));
255 web_idb_factory_
.reset(new WebIDBFactoryImpl(thread_safe_sender_
.get()));
256 web_database_observer_impl_
.reset(
257 new WebDatabaseObserverImpl(sync_message_filter_
.get()));
261 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
262 WebFileSystemImpl::DeleteThreadSpecificInstance();
265 //------------------------------------------------------------------------------
267 blink::WebThread
* RendererBlinkPlatformImpl::currentThread() {
268 if (main_thread_
->isCurrentThread())
269 return main_thread_
.get();
270 return BlinkPlatformImpl::currentThread();
273 blink::WebClipboard
* RendererBlinkPlatformImpl::clipboard() {
274 blink::WebClipboard
* clipboard
=
275 GetContentClient()->renderer()->OverrideWebClipboard();
278 return clipboard_
.get();
281 blink::WebMimeRegistry
* RendererBlinkPlatformImpl::mimeRegistry() {
282 return mime_registry_
.get();
285 blink::WebFileUtilities
* RendererBlinkPlatformImpl::fileUtilities() {
286 if (!file_utilities_
) {
287 file_utilities_
.reset(new FileUtilities(thread_safe_sender_
.get()));
288 file_utilities_
->set_sandbox_enabled(sandboxEnabled());
290 return file_utilities_
.get();
293 blink::WebSandboxSupport
* RendererBlinkPlatformImpl::sandboxSupport() {
294 #if defined(OS_ANDROID) || defined(OS_WIN)
295 // These platforms do not require sandbox support.
298 return sandbox_support_
.get();
302 blink::WebCookieJar
* RendererBlinkPlatformImpl::cookieJar() {
303 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
307 blink::WebThemeEngine
* RendererBlinkPlatformImpl::themeEngine() {
308 blink::WebThemeEngine
* theme_engine
=
309 GetContentClient()->renderer()->OverrideThemeEngine();
312 return BlinkPlatformImpl::themeEngine();
315 bool RendererBlinkPlatformImpl::sandboxEnabled() {
316 // As explained in Platform.h, this function is used to decide
317 // whether to allow file system operations to come out of WebKit or not.
318 // Even if the sandbox is disabled, there's no reason why the code should
319 // act any differently...unless we're in single process mode. In which
320 // case, we have no other choice. Platform.h discourages using
321 // this switch unless absolutely necessary, so hopefully we won't end up
322 // with too many code paths being different in single-process mode.
323 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
324 switches::kSingleProcess
);
327 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
328 const char* canonical_url
,
330 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url
, length
);
333 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash
) {
334 return GetContentClient()->renderer()->IsLinkVisited(link_hash
);
337 void RendererBlinkPlatformImpl::createMessageChannel(
338 blink::WebMessagePortChannel
** channel1
,
339 blink::WebMessagePortChannel
** channel2
) {
340 WebMessagePortChannelImpl::CreatePair(
341 default_task_runner_
, channel1
, channel2
);
344 blink::WebPrescientNetworking
*
345 RendererBlinkPlatformImpl::prescientNetworking() {
346 return GetContentClient()->renderer()->GetPrescientNetworking();
349 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL
& url
,
353 // Let the browser know we generated cacheable metadata for this resource. The
354 // browser may cache it and return it on subsequent responses to speed
355 // the processing of this resource.
356 std::vector
<char> copy(data
, data
+ size
);
357 RenderThread::Get()->Send(new ViewHostMsg_DidGenerateCacheableMetadata(
358 url
, base::Time::FromInternalValue(response_time
), copy
));
361 WebString
RendererBlinkPlatformImpl::defaultLocale() {
362 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
365 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled
) {
367 // We should not get more enables than disables, but we want it to be a
368 // non-fatal error if it does happen.
369 DCHECK_GT(sudden_termination_disables_
, 0);
370 sudden_termination_disables_
= std::max(sudden_termination_disables_
- 1,
372 if (sudden_termination_disables_
!= 0)
375 sudden_termination_disables_
++;
376 if (sudden_termination_disables_
!= 1)
380 RenderThread
* thread
= RenderThread::Get();
381 if (thread
) // NULL in unittests.
382 thread
->Send(new ViewHostMsg_SuddenTerminationChanged(enabled
));
385 WebStorageNamespace
* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
386 return new WebStorageNamespaceImpl();
390 //------------------------------------------------------------------------------
392 WebIDBFactory
* RendererBlinkPlatformImpl::idbFactory() {
393 return web_idb_factory_
.get();
396 //------------------------------------------------------------------------------
398 blink::WebServiceWorkerCacheStorage
* RendererBlinkPlatformImpl::cacheStorage(
399 const WebString
& origin_identifier
) {
401 storage::GetOriginFromIdentifier(origin_identifier
.utf8());
402 return new WebServiceWorkerCacheStorageImpl(thread_safe_sender_
.get(),
406 //------------------------------------------------------------------------------
408 WebFileSystem
* RendererBlinkPlatformImpl::fileSystem() {
409 return WebFileSystemImpl::ThreadSpecificInstance(default_task_runner_
);
412 //------------------------------------------------------------------------------
414 WebMimeRegistry::SupportsType
415 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
416 const WebString
& mime_type
,
417 const WebString
& codecs
,
418 const WebString
& key_system
) {
419 const std::string mime_type_ascii
= ToASCIIOrEmpty(mime_type
);
420 // Not supporting the container is a flat-out no.
421 if (!media::IsSupportedMediaMimeType(mime_type_ascii
))
422 return IsNotSupported
;
424 if (!key_system
.isEmpty()) {
425 // Check whether the key system is supported with the mime_type and codecs.
427 // Chromium only supports ASCII parameters.
428 if (!base::IsStringASCII(key_system
))
429 return IsNotSupported
;
431 std::string key_system_ascii
=
432 media::GetUnprefixedKeySystemName(base::UTF16ToASCII(
433 base::StringPiece16(key_system
)));
434 std::vector
<std::string
> strict_codecs
;
435 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &strict_codecs
, true);
437 if (!media::PrefixedIsSupportedKeySystemWithMediaMimeType(
438 mime_type_ascii
, strict_codecs
, key_system_ascii
)) {
439 return IsNotSupported
;
442 // Continue processing the mime_type and codecs.
445 // Check list of strict codecs to see if it is supported.
446 if (media::IsStrictMediaMimeType(mime_type_ascii
)) {
447 // Check if the codecs are a perfect match.
448 std::vector
<std::string
> strict_codecs
;
449 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &strict_codecs
, false);
450 return static_cast<WebMimeRegistry::SupportsType
> (
451 media::IsSupportedStrictMediaMimeType(mime_type_ascii
, strict_codecs
));
454 // If we don't recognize the codec, it's possible we support it.
455 std::vector
<std::string
> parsed_codecs
;
456 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &parsed_codecs
, true);
457 if (!media::AreSupportedMediaCodecs(parsed_codecs
))
458 return MayBeSupported
;
460 // Otherwise we have a perfect match.
464 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
465 const blink::WebString
& mime_type
,
466 const WebString
& codecs
) {
467 const std::string mime_type_ascii
= ToASCIIOrEmpty(mime_type
);
468 std::vector
<std::string
> parsed_codec_ids
;
469 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &parsed_codec_ids
, false);
470 if (mime_type_ascii
.empty())
472 return media::StreamParserFactory::IsTypeSupported(
473 mime_type_ascii
, parsed_codec_ids
);
476 WebString
RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
477 const WebString
& file_extension
) {
478 if (IsPluginProcess())
479 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension
);
481 // The sandbox restricts our access to the registry, so we need to proxy
482 // these calls over to the browser process.
483 std::string mime_type
;
484 RenderThread::Get()->Send(
485 new MimeRegistryMsg_GetMimeTypeFromExtension(
486 base::FilePath::FromUTF16Unsafe(file_extension
).value(), &mime_type
));
487 return base::ASCIIToUTF16(mime_type
);
490 WebString
RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
491 const WebString
& file_path
) {
492 if (IsPluginProcess())
493 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path
);
495 // The sandbox restricts our access to the registry, so we need to proxy
496 // these calls over to the browser process.
497 std::string mime_type
;
498 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
499 base::FilePath::FromUTF16Unsafe(file_path
),
501 return base::ASCIIToUTF16(mime_type
);
504 //------------------------------------------------------------------------------
506 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
507 const WebString
& path
,
508 WebFileInfo
& web_file_info
) {
509 base::File::Info file_info
;
510 base::File::Error status
= base::File::FILE_ERROR_MAX
;
511 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
512 base::FilePath::FromUTF16Unsafe(path
), &file_info
, &status
)) ||
513 status
!= base::File::FILE_OK
) {
516 FileInfoToWebFileInfo(file_info
, &web_file_info
);
517 web_file_info
.platformPath
= path
;
521 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
522 IPC::SyncMessage
* msg
) const {
523 base::TimeTicks begin
= base::TimeTicks::Now();
524 const bool success
= thread_safe_sender_
->Send(msg
);
525 base::TimeDelta delta
= base::TimeTicks::Now() - begin
;
526 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta
);
530 //------------------------------------------------------------------------------
532 #if defined(OS_MACOSX)
534 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont
* src_font
,
537 uint32 font_data_size
;
538 FontDescriptor
src_font_descriptor(src_font
);
539 base::SharedMemoryHandle font_data
;
540 if (!RenderThread::Get()->Send(new FrameHostMsg_LoadFont(
541 src_font_descriptor
, &font_data_size
, &font_data
, font_id
))) {
547 if (font_data_size
== 0 || font_data
== base::SharedMemory::NULLHandle() ||
549 LOG(ERROR
) << "Bad response from FrameHostMsg_LoadFont() for " <<
550 src_font_descriptor
.font_name
;
556 // TODO(jeremy): Need to call back into WebKit to make sure that the font
557 // isn't already activated, based on the font id. If it's already
558 // activated, don't reactivate it here - crbug.com/72727 .
560 return FontLoader::CGFontRefFromBuffer(font_data
, font_data_size
, out
);
563 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
565 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
566 blink::WebUChar32 character
,
567 const char* preferred_locale
,
568 blink::WebFallbackFont
* fallbackFont
) {
569 base::AutoLock
lock(unicode_font_families_mutex_
);
570 const std::map
<int32_t, blink::WebFallbackFont
>::const_iterator iter
=
571 unicode_font_families_
.find(character
);
572 if (iter
!= unicode_font_families_
.end()) {
573 fallbackFont
->name
= iter
->second
.name
;
574 fallbackFont
->filename
= iter
->second
.filename
;
575 fallbackFont
->fontconfigInterfaceId
= iter
->second
.fontconfigInterfaceId
;
576 fallbackFont
->ttcIndex
= iter
->second
.ttcIndex
;
577 fallbackFont
->isBold
= iter
->second
.isBold
;
578 fallbackFont
->isItalic
= iter
->second
.isItalic
;
582 GetFallbackFontForCharacter(character
, preferred_locale
, fallbackFont
);
583 unicode_font_families_
.insert(std::make_pair(character
, *fallbackFont
));
586 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
589 blink::WebFontRenderStyle
* out
) {
590 GetRenderStyleForStrike(family
, sizeAndStyle
, out
);
595 //------------------------------------------------------------------------------
597 Platform::FileHandle
RendererBlinkPlatformImpl::databaseOpenFile(
598 const WebString
& vfs_file_name
,
600 return DatabaseUtil::DatabaseOpenFile(
601 vfs_file_name
, desired_flags
, sync_message_filter_
.get());
604 int RendererBlinkPlatformImpl::databaseDeleteFile(
605 const WebString
& vfs_file_name
,
607 return DatabaseUtil::DatabaseDeleteFile(
608 vfs_file_name
, sync_dir
, sync_message_filter_
.get());
611 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
612 const WebString
& vfs_file_name
) {
613 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name
,
614 sync_message_filter_
.get());
617 long long RendererBlinkPlatformImpl::databaseGetFileSize(
618 const WebString
& vfs_file_name
) {
619 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name
,
620 sync_message_filter_
.get());
623 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
624 const WebString
& origin_identifier
) {
625 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier
,
626 sync_message_filter_
.get());
629 bool RendererBlinkPlatformImpl::databaseSetFileSize(
630 const WebString
& vfs_file_name
, long long size
) {
631 return DatabaseUtil::DatabaseSetFileSize(
632 vfs_file_name
, size
, sync_message_filter_
.get());
635 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
636 #if defined(OS_ANDROID)
637 SynchronousCompositorFactory
* factory
=
638 SynchronousCompositorFactory::GetInstance();
639 if (factory
&& factory
->OverrideWithFactory()) {
640 return factory
->GetGPUInfo().SupportsAccelerated2dCanvas();
644 RenderThreadImpl
* thread
= RenderThreadImpl::current();
645 GpuChannelHost
* host
= thread
->EstablishGpuChannelSync(
646 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D
);
650 return host
->gpu_info().SupportsAccelerated2dCanvas();
653 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
654 RenderThreadImpl
* thread
= RenderThreadImpl::current();
655 // thread can be NULL in tests.
656 return thread
&& thread
->compositor_task_runner().get();
659 bool RendererBlinkPlatformImpl::isThreadedAnimationEnabled() {
660 RenderThreadImpl
* thread
= RenderThreadImpl::current();
661 return thread
? thread
->IsThreadedAnimationEnabled() : true;
664 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
665 RenderThreadImpl
* thread
= RenderThreadImpl::current();
666 return thread
->GetAudioHardwareConfig()->GetOutputSampleRate();
669 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
670 RenderThreadImpl
* thread
= RenderThreadImpl::current();
671 return thread
->GetAudioHardwareConfig()->GetOutputBufferSize();
674 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
675 RenderThreadImpl
* thread
= RenderThreadImpl::current();
676 return thread
->GetAudioHardwareConfig()->GetOutputChannels();
679 WebDatabaseObserver
* RendererBlinkPlatformImpl::databaseObserver() {
680 return web_database_observer_impl_
.get();
683 WebAudioDevice
* RendererBlinkPlatformImpl::createAudioDevice(
685 unsigned input_channels
,
688 WebAudioDevice::RenderCallback
* callback
,
689 const blink::WebString
& input_device_id
) {
690 // Use a mock for testing.
691 blink::WebAudioDevice
* mock_device
=
692 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate
);
696 // The |channels| does not exactly identify the channel layout of the
697 // device. The switch statement below assigns a best guess to the channel
698 // layout based on number of channels.
699 media::ChannelLayout layout
= media::CHANNEL_LAYOUT_UNSUPPORTED
;
702 layout
= media::CHANNEL_LAYOUT_MONO
;
705 layout
= media::CHANNEL_LAYOUT_STEREO
;
708 layout
= media::CHANNEL_LAYOUT_2_1
;
711 layout
= media::CHANNEL_LAYOUT_4_0
;
714 layout
= media::CHANNEL_LAYOUT_5_0
;
717 layout
= media::CHANNEL_LAYOUT_5_1
;
720 layout
= media::CHANNEL_LAYOUT_7_0
;
723 layout
= media::CHANNEL_LAYOUT_7_1
;
726 // If the layout is not supported (more than 9 channels), falls back to
728 layout
= media::CHANNEL_LAYOUT_DISCRETE
;
732 if (input_device_id
.isNull() ||
733 !base::StringToInt(base::UTF16ToUTF8(
734 base::StringPiece16(input_device_id
)), &session_id
)) {
735 if (input_channels
> 0)
736 DLOG(WARNING
) << "createAudioDevice(): request for audio input ignored";
741 // For CHANNEL_LAYOUT_DISCRETE, pass the explicit channel count along with
742 // the channel layout when creating an |AudioParameters| object.
743 media::AudioParameters
params(media::AudioParameters::AUDIO_PCM_LOW_LATENCY
,
744 layout
, static_cast<int>(sample_rate
), 16,
746 params
.set_channels_for_discrete(channels
);
748 return new RendererWebAudioDeviceImpl(params
, callback
, session_id
);
751 #if defined(OS_ANDROID)
752 bool RendererBlinkPlatformImpl::loadAudioResource(
753 blink::WebAudioBus
* destination_bus
,
754 const char* audio_file_data
,
756 return DecodeAudioFileData(destination_bus
,
759 thread_safe_sender_
);
762 bool RendererBlinkPlatformImpl::loadAudioResource(
763 blink::WebAudioBus
* destination_bus
,
764 const char* audio_file_data
,
766 return DecodeAudioFileData(
767 destination_bus
, audio_file_data
, data_size
);
769 #endif // defined(OS_ANDROID)
771 //------------------------------------------------------------------------------
773 blink::WebMIDIAccessor
* RendererBlinkPlatformImpl::createMIDIAccessor(
774 blink::WebMIDIAccessorClient
* client
) {
775 blink::WebMIDIAccessor
* accessor
=
776 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client
);
780 return new RendererWebMIDIAccessorImpl(client
);
783 void RendererBlinkPlatformImpl::getPluginList(
785 blink::WebPluginListBuilder
* builder
) {
786 #if defined(ENABLE_PLUGINS)
787 std::vector
<WebPluginInfo
> plugins
;
788 if (!plugin_refresh_allowed_
)
790 RenderThread::Get()->Send(new FrameHostMsg_GetPlugins(refresh
, &plugins
));
791 for (const WebPluginInfo
& plugin
: plugins
) {
793 plugin
.name
, plugin
.desc
,
794 plugin
.path
.BaseName().AsUTF16Unsafe());
796 for (const WebPluginMimeType
& mime_type
: plugin
.mime_types
) {
797 builder
->addMediaTypeToLastPlugin(
798 WebString::fromUTF8(mime_type
.mime_type
), mime_type
.description
);
800 for (const auto& extension
: mime_type
.file_extensions
) {
801 builder
->addFileExtensionToLastMediaType(
802 WebString::fromUTF8(extension
));
809 //------------------------------------------------------------------------------
811 blink::WebPublicSuffixList
* RendererBlinkPlatformImpl::publicSuffixList() {
812 return &public_suffix_list_
;
815 //------------------------------------------------------------------------------
817 blink::WebString
RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
818 unsigned key_size_index
,
819 const blink::WebString
& challenge
,
820 const blink::WebURL
& url
) {
821 std::string signed_public_key
;
822 RenderThread::Get()->Send(new FrameHostMsg_Keygen(
823 static_cast<uint32
>(key_size_index
),
826 &signed_public_key
));
827 return WebString::fromUTF8(signed_public_key
);
830 //------------------------------------------------------------------------------
832 void RendererBlinkPlatformImpl::screenColorProfile(
833 WebVector
<char>* to_profile
) {
835 // On Windows screen color profile is only available in the browser.
836 std::vector
<char> profile
;
837 // This Send() can be called from any impl-side thread. Use a thread
838 // safe send to avoid crashing trying to access RenderThread::Get(),
839 // which is not accessible from arbitrary threads.
840 thread_safe_sender_
->Send(
841 new ViewHostMsg_GetMonitorColorProfile(&profile
));
842 *to_profile
= profile
;
844 // On other platforms, the primary monitor color profile can be read
846 gfx::ColorProfile profile
;
847 *to_profile
= profile
.profile();
851 //------------------------------------------------------------------------------
853 blink::WebScrollbarBehavior
* RendererBlinkPlatformImpl::scrollbarBehavior() {
854 return web_scrollbar_behavior_
.get();
857 //------------------------------------------------------------------------------
859 WebBlobRegistry
* RendererBlinkPlatformImpl::blobRegistry() {
860 // blob_registry_ can be NULL when running some tests.
861 return blob_registry_
.get();
864 //------------------------------------------------------------------------------
866 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads
& gamepads
) {
867 PlatformEventObserverBase
* observer
=
868 platform_event_observers_
.Lookup(blink::WebPlatformEventGamepad
);
871 static_cast<RendererGamepadProvider
*>(observer
)->SampleGamepads(gamepads
);
874 //------------------------------------------------------------------------------
876 WebMediaRecorderHandler
*
877 RendererBlinkPlatformImpl::createMediaRecorderHandler() {
878 #if !defined(OS_ANDROID)
879 return new content::MediaRecorderHandler();
885 //------------------------------------------------------------------------------
887 WebRTCPeerConnectionHandler
*
888 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
889 WebRTCPeerConnectionHandlerClient
* client
) {
890 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
891 DCHECK(render_thread
);
895 #if defined(ENABLE_WEBRTC)
896 WebRTCPeerConnectionHandler
* peer_connection_handler
=
897 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
899 if (peer_connection_handler
)
900 return peer_connection_handler
;
902 PeerConnectionDependencyFactory
* rtc_dependency_factory
=
903 render_thread
->GetPeerConnectionDependencyFactory();
904 return rtc_dependency_factory
->CreateRTCPeerConnectionHandler(client
);
907 #endif // defined(ENABLE_WEBRTC)
910 //------------------------------------------------------------------------------
912 WebMediaStreamCenter
* RendererBlinkPlatformImpl::createMediaStreamCenter(
913 WebMediaStreamCenterClient
* client
) {
914 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
915 DCHECK(render_thread
);
918 return render_thread
->CreateMediaStreamCenter(client
);
922 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable
) {
923 bool was_enabled
= g_sandbox_enabled
;
924 g_sandbox_enabled
= enable
;
928 //------------------------------------------------------------------------------
930 blink::WebSpeechSynthesizer
* RendererBlinkPlatformImpl::createSpeechSynthesizer(
931 blink::WebSpeechSynthesizerClient
* client
) {
932 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client
);
935 //------------------------------------------------------------------------------
937 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
938 size_t* private_bytes
,
939 size_t* shared_bytes
) {
940 content::RenderThread::Get()->Send(
941 new ViewHostMsg_GetProcessMemorySizes(private_bytes
, shared_bytes
));
945 //------------------------------------------------------------------------------
947 blink::WebGraphicsContext3D
*
948 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
949 const blink::WebGraphicsContext3D::Attributes
& attributes
) {
950 return createOffscreenGraphicsContext3D(attributes
, NULL
);
953 blink::WebGraphicsContext3D
*
954 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
955 const blink::WebGraphicsContext3D::Attributes
& attributes
,
956 blink::WebGraphicsContext3D
* share_context
) {
957 return createOffscreenGraphicsContext3D(attributes
, share_context
, NULL
);
960 blink::WebGraphicsContext3D
*
961 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
962 const blink::WebGraphicsContext3D::Attributes
& attributes
,
963 blink::WebGraphicsContext3D
* share_context
,
964 blink::WebGLInfo
* gl_info
) {
965 if (!RenderThreadImpl::current())
968 #if defined(OS_ANDROID)
969 SynchronousCompositorFactory
* factory
=
970 SynchronousCompositorFactory::GetInstance();
971 if (factory
&& factory
->OverrideWithFactory()) {
972 scoped_ptr
<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl
>
974 factory
->CreateOffscreenGraphicsContext3D(attributes
));
975 if (!in_process_context
|| !in_process_context
->InitializeOnCurrentThread())
977 return in_process_context
.release();
981 scoped_refptr
<GpuChannelHost
> gpu_channel_host(
982 RenderThreadImpl::current()->EstablishGpuChannelSync(
983 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
985 if (gpu_channel_host
.get() && gl_info
) {
986 const gpu::GPUInfo
& gpu_info
= gpu_channel_host
->gpu_info();
987 switch (gpu_info
.context_info_state
) {
988 case gpu::kCollectInfoSuccess
:
989 case gpu::kCollectInfoNonFatalFailure
:
990 gl_info
->vendorInfo
.assign(
991 blink::WebString::fromUTF8(gpu_info
.gl_vendor
));
992 gl_info
->rendererInfo
.assign(
993 blink::WebString::fromUTF8(gpu_info
.gl_renderer
));
994 gl_info
->driverVersion
.assign(
995 blink::WebString::fromUTF8(gpu_info
.driver_version
));
996 gl_info
->vendorId
= gpu_info
.gpu
.vendor_id
;
997 gl_info
->deviceId
= gpu_info
.gpu
.device_id
;
999 case gpu::kCollectInfoFatalFailure
:
1000 case gpu::kCollectInfoNone
:
1001 gl_info
->contextInfoCollectionFailure
.assign(blink::WebString::fromUTF8(
1002 "GPUInfoCollectionFailure: GPU initialization Failed. GPU "
1003 "Info not Collected."));
1010 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits
;
1011 bool lose_context_when_out_of_memory
= false;
1012 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
> context(
1013 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1014 gpu_channel_host
.get(),
1016 lose_context_when_out_of_memory
,
1017 GURL(attributes
.topDocumentURL
),
1019 static_cast<WebGraphicsContext3DCommandBufferImpl
*>(share_context
)));
1021 // Most likely the GPU process exited and the attempt to reconnect to it
1022 // failed. Need to try to restore the context again later.
1023 if (!context
|| !context
->InitializeOnCurrentThread())
1025 return context
.release();
1028 //------------------------------------------------------------------------------
1030 blink::WebGraphicsContext3DProvider
*
1031 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
1032 scoped_refptr
<cc_blink::ContextProviderWebContext
> provider
=
1033 RenderThreadImpl::current()->SharedMainThreadContextProvider();
1034 if (!provider
.get())
1036 return new WebGraphicsContext3DProviderImpl(provider
);
1039 //------------------------------------------------------------------------------
1041 blink::WebCompositorSupport
* RendererBlinkPlatformImpl::compositorSupport() {
1042 return &compositor_support_
;
1045 //------------------------------------------------------------------------------
1047 blink::WebString
RendererBlinkPlatformImpl::convertIDNToUnicode(
1048 const blink::WebString
& host
,
1049 const blink::WebString
& languages
) {
1050 return url_formatter::IDNToUnicode(host
.utf8(), languages
.utf8());
1053 //------------------------------------------------------------------------------
1055 void RendererBlinkPlatformImpl::recordRappor(const char* metric
,
1056 const blink::WebString
& sample
) {
1057 GetContentClient()->renderer()->RecordRappor(metric
, sample
.utf8());
1060 void RendererBlinkPlatformImpl::recordRapporURL(const char* metric
,
1061 const blink::WebURL
& url
) {
1062 GetContentClient()->renderer()->RecordRapporURL(metric
, url
);
1065 //------------------------------------------------------------------------------
1068 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data
) {
1069 g_test_device_light_data
= data
;
1072 //------------------------------------------------------------------------------
1075 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1076 const blink::WebDeviceMotionData
& data
) {
1077 g_test_device_motion_data
.Get() = data
;
1080 //------------------------------------------------------------------------------
1083 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1084 const blink::WebDeviceOrientationData
& data
) {
1085 g_test_device_orientation_data
.Get() = data
;
1088 //------------------------------------------------------------------------------
1090 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds
) {
1091 GetConnectedVibrationManagerService()->Vibrate(
1092 base::checked_cast
<int64
>(milliseconds
));
1093 vibration_manager_
.reset();
1096 void RendererBlinkPlatformImpl::cancelVibration() {
1097 GetConnectedVibrationManagerService()->Cancel();
1098 vibration_manager_
.reset();
1101 device::VibrationManagerPtr
&
1102 RendererBlinkPlatformImpl::GetConnectedVibrationManagerService() {
1103 if (!vibration_manager_
) {
1104 RenderThread::Get()->GetServiceRegistry()->ConnectToRemoteService(
1105 mojo::GetProxy(&vibration_manager_
));
1107 return vibration_manager_
;
1110 //------------------------------------------------------------------------------
1113 PlatformEventObserverBase
*
1114 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1115 blink::WebPlatformEventType type
) {
1116 RenderThread
* thread
= RenderThreadImpl::current();
1118 // When running layout tests, those observers should not listen to the actual
1119 // hardware changes. In order to make that happen, they will receive a null
1121 if (thread
&& RenderThreadImpl::current()->layout_test_mode())
1125 case blink::WebPlatformEventDeviceMotion
:
1126 return new DeviceMotionEventPump(thread
);
1127 case blink::WebPlatformEventDeviceOrientation
:
1128 return new DeviceOrientationEventPump(thread
);
1129 case blink::WebPlatformEventDeviceLight
:
1130 return new DeviceLightEventPump(thread
);
1131 case blink::WebPlatformEventGamepad
:
1132 return new GamepadSharedMemoryReader(thread
);
1133 case blink::WebPlatformEventScreenOrientation
:
1134 return new ScreenOrientationObserver();
1136 // A default statement is required to prevent compilation errors when
1137 // Blink adds a new type.
1138 DVLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1145 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1146 blink::WebPlatformEventType type
,
1147 scoped_ptr
<PlatformEventObserverBase
> observer
) {
1148 DCHECK(type
!= blink::WebPlatformEventBattery
);
1150 if (platform_event_observers_
.Lookup(type
))
1151 platform_event_observers_
.Remove(type
);
1152 platform_event_observers_
.AddWithID(observer
.release(), type
);
1155 void RendererBlinkPlatformImpl::startListening(
1156 blink::WebPlatformEventType type
,
1157 blink::WebPlatformEventListener
* listener
) {
1158 if (type
== blink::WebPlatformEventBattery
) {
1159 if (RenderThreadImpl::current() &&
1160 RenderThreadImpl::current()->layout_test_mode()) {
1161 g_test_battery_status_listener
=
1162 static_cast<blink::WebBatteryStatusListener
*>(listener
);
1164 battery_status_dispatcher_
.reset(new BatteryStatusDispatcher(
1165 static_cast<blink::WebBatteryStatusListener
*>(listener
)));
1170 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1172 observer
= CreatePlatformEventObserverFromType(type
);
1175 platform_event_observers_
.AddWithID(observer
, static_cast<int32
>(type
));
1177 observer
->Start(listener
);
1179 // Device events (motion, orientation and light) expect to get an event fired
1180 // as soon as a listener is registered if a fake data was passed before.
1181 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1182 // using this broken pattern.
1183 if (RenderThreadImpl::current() &&
1184 RenderThreadImpl::current()->layout_test_mode() &&
1185 (type
== blink::WebPlatformEventDeviceMotion
||
1186 type
== blink::WebPlatformEventDeviceOrientation
||
1187 type
== blink::WebPlatformEventDeviceLight
)) {
1188 SendFakeDeviceEventDataForTesting(type
);
1192 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1193 blink::WebPlatformEventType type
) {
1194 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1200 case blink::WebPlatformEventDeviceMotion
:
1201 if (!(g_test_device_motion_data
== 0))
1202 data
= &g_test_device_motion_data
.Get();
1204 case blink::WebPlatformEventDeviceOrientation
:
1205 if (!(g_test_device_orientation_data
== 0))
1206 data
= &g_test_device_orientation_data
.Get();
1208 case blink::WebPlatformEventDeviceLight
:
1209 if (g_test_device_light_data
>= 0)
1210 data
= &g_test_device_light_data
;
1220 base::ThreadTaskRunnerHandle::Get()->PostTask(
1221 FROM_HERE
, base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting
,
1222 base::Unretained(observer
), data
));
1225 void RendererBlinkPlatformImpl::stopListening(
1226 blink::WebPlatformEventType type
) {
1227 if (type
== blink::WebPlatformEventBattery
) {
1228 g_test_battery_status_listener
= nullptr;
1229 battery_status_dispatcher_
.reset();
1233 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1239 //------------------------------------------------------------------------------
1241 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1242 const blink::WebURL
& storage_partition
,
1243 blink::WebStorageQuotaType type
,
1244 blink::WebStorageQuotaCallbacks callbacks
) {
1245 if (!thread_safe_sender_
.get() || !quota_message_filter_
.get())
1247 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_
.get(),
1248 quota_message_filter_
.get())
1249 ->QueryStorageUsageAndQuota(
1251 static_cast<storage::StorageType
>(type
),
1252 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
1255 //------------------------------------------------------------------------------
1257 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1258 const blink::WebBatteryStatus
& status
) {
1259 if (!g_test_battery_status_listener
)
1261 g_test_battery_status_listener
->updateBatteryStatus(status
);
1264 } // namespace content