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/renderer_webaudiodevice_impl.h"
59 #include "content/renderer/media/renderer_webmidiaccessor_impl.h"
60 #include "content/renderer/render_thread_impl.h"
61 #include "content/renderer/renderer_clipboard_delegate.h"
62 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
63 #include "content/renderer/webclipboard_impl.h"
64 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
65 #include "content/renderer/webpublicsuffixlist_impl.h"
66 #include "gpu/config/gpu_info.h"
67 #include "ipc/ipc_sync_message_filter.h"
68 #include "media/audio/audio_output_device.h"
69 #include "media/base/audio_hardware_config.h"
70 #include "media/base/key_systems.h"
71 #include "media/base/mime_util.h"
72 #include "media/blink/webcontentdecryptionmodule_impl.h"
73 #include "media/filters/stream_parser_factory.h"
74 #include "storage/common/database/database_identifier.h"
75 #include "storage/common/quota/quota_types.h"
76 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
77 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
78 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
79 #include "third_party/WebKit/public/platform/WebFileInfo.h"
80 #include "third_party/WebKit/public/platform/WebGamepads.h"
81 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
82 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
83 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
84 #include "third_party/WebKit/public/platform/WebURL.h"
85 #include "third_party/WebKit/public/platform/WebVector.h"
86 #include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionListener.h"
87 #include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationListener.h"
88 #include "ui/gfx/color_profile.h"
91 #if defined(OS_ANDROID)
92 #include "content/renderer/android/synchronous_compositor_factory.h"
93 #include "content/renderer/media/android/audio_decoder_android.h"
94 #include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h"
97 #if defined(OS_MACOSX)
98 #include "content/common/mac/font_descriptor.h"
99 #include "content/common/mac/font_loader.h"
100 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
101 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
104 #if defined(OS_POSIX)
105 #include "base/file_descriptor_posix.h"
106 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
110 #include "base/synchronization/lock.h"
111 #include "content/common/child_process_sandbox_support_impl_linux.h"
112 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
113 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
114 #include "third_party/icu/source/common/unicode/utf16.h"
119 #include "content/common/child_process_messages.h"
122 #if defined(USE_AURA)
123 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
124 #elif !defined(OS_MACOSX)
125 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
126 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
129 #if defined(ENABLE_WEBRTC)
130 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
133 using blink::Platform
;
134 using blink::WebAudioDevice
;
135 using blink::WebBlobRegistry
;
136 using blink::WebDatabaseObserver
;
137 using blink::WebFileInfo
;
138 using blink::WebFileSystem
;
139 using blink::WebGamepad
;
140 using blink::WebGamepads
;
141 using blink::WebIDBFactory
;
142 using blink::WebMIDIAccessor
;
143 using blink::WebMediaStreamCenter
;
144 using blink::WebMediaStreamCenterClient
;
145 using blink::WebMimeRegistry
;
146 using blink::WebRTCPeerConnectionHandler
;
147 using blink::WebRTCPeerConnectionHandlerClient
;
148 using blink::WebStorageNamespace
;
149 using blink::WebString
;
151 using blink::WebVector
;
157 bool g_sandbox_enabled
= true;
158 double g_test_device_light_data
= -1;
159 base::LazyInstance
<blink::WebDeviceMotionData
>::Leaky
160 g_test_device_motion_data
= LAZY_INSTANCE_INITIALIZER
;
161 base::LazyInstance
<blink::WebDeviceOrientationData
>::Leaky
162 g_test_device_orientation_data
= LAZY_INSTANCE_INITIALIZER
;
163 // Set in startListening() when running layout tests, unset in stopListening(),
165 blink::WebBatteryStatusListener
* g_test_battery_status_listener
= nullptr;
169 //------------------------------------------------------------------------------
171 class RendererBlinkPlatformImpl::MimeRegistry
172 : public SimpleWebMimeRegistryImpl
{
174 virtual blink::WebMimeRegistry::SupportsType
supportsMediaMIMEType(
175 const blink::WebString
& mime_type
,
176 const blink::WebString
& codecs
,
177 const blink::WebString
& key_system
);
178 virtual bool supportsMediaSourceMIMEType(const blink::WebString
& mime_type
,
179 const blink::WebString
& codecs
);
180 virtual blink::WebString
mimeTypeForExtension(
181 const blink::WebString
& file_extension
);
182 virtual blink::WebString
mimeTypeFromFile(
183 const blink::WebString
& file_path
);
186 class RendererBlinkPlatformImpl::FileUtilities
: public WebFileUtilitiesImpl
{
188 explicit FileUtilities(ThreadSafeSender
* sender
)
189 : thread_safe_sender_(sender
) {}
190 virtual bool getFileInfo(const WebString
& path
, WebFileInfo
& result
);
192 bool SendSyncMessageFromAnyThread(IPC::SyncMessage
* msg
) const;
193 scoped_refptr
<ThreadSafeSender
> thread_safe_sender_
;
196 #if !defined(OS_ANDROID) && !defined(OS_WIN)
197 class RendererBlinkPlatformImpl::SandboxSupport
198 : public blink::WebSandboxSupport
{
200 virtual ~SandboxSupport() {}
202 #if defined(OS_MACOSX)
203 virtual bool loadFont(
205 CGFontRef
* container
,
207 #elif defined(OS_POSIX)
208 virtual void getFallbackFontForCharacter(
209 blink::WebUChar32 character
,
210 const char* preferred_locale
,
211 blink::WebFallbackFont
* fallbackFont
);
212 virtual void getRenderStyleForStrike(
213 const char* family
, int sizeAndStyle
, blink::WebFontRenderStyle
* out
);
216 // WebKit likes to ask us for the correct font family to use for a set of
217 // unicode code points. It needs this information frequently so we cache it
219 base::Lock unicode_font_families_mutex_
;
220 std::map
<int32_t, blink::WebFallbackFont
> unicode_font_families_
;
223 #endif // !defined(OS_ANDROID) && !defined(OS_WIN)
225 //------------------------------------------------------------------------------
227 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
228 scheduler::RendererScheduler
* renderer_scheduler
)
229 : BlinkPlatformImpl(renderer_scheduler
->DefaultTaskRunner()),
231 new scheduler::WebThreadImplForRendererScheduler(renderer_scheduler
)),
232 clipboard_delegate_(new RendererClipboardDelegate
),
233 clipboard_(new WebClipboardImpl(clipboard_delegate_
.get())),
234 mime_registry_(new RendererBlinkPlatformImpl::MimeRegistry
),
235 sudden_termination_disables_(0),
236 plugin_refresh_allowed_(true),
237 default_task_runner_(renderer_scheduler
->DefaultTaskRunner()),
238 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl
) {
239 #if !defined(OS_ANDROID) && !defined(OS_WIN)
240 if (g_sandbox_enabled
&& sandboxEnabled()) {
241 sandbox_support_
.reset(new RendererBlinkPlatformImpl::SandboxSupport
);
243 DVLOG(1) << "Disabling sandbox support for testing.";
247 // ChildThread may not exist in some tests.
248 if (ChildThreadImpl::current()) {
249 sync_message_filter_
= ChildThreadImpl::current()->sync_message_filter();
250 thread_safe_sender_
= ChildThreadImpl::current()->thread_safe_sender();
251 quota_message_filter_
= ChildThreadImpl::current()->quota_message_filter();
252 blob_registry_
.reset(new WebBlobRegistryImpl(thread_safe_sender_
.get()));
253 web_idb_factory_
.reset(new WebIDBFactoryImpl(thread_safe_sender_
.get()));
254 web_database_observer_impl_
.reset(
255 new WebDatabaseObserverImpl(sync_message_filter_
.get()));
259 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
260 WebFileSystemImpl::DeleteThreadSpecificInstance();
263 //------------------------------------------------------------------------------
265 blink::WebThread
* RendererBlinkPlatformImpl::currentThread() {
266 if (main_thread_
->isCurrentThread())
267 return main_thread_
.get();
268 return BlinkPlatformImpl::currentThread();
271 blink::WebClipboard
* RendererBlinkPlatformImpl::clipboard() {
272 blink::WebClipboard
* clipboard
=
273 GetContentClient()->renderer()->OverrideWebClipboard();
276 return clipboard_
.get();
279 blink::WebMimeRegistry
* RendererBlinkPlatformImpl::mimeRegistry() {
280 return mime_registry_
.get();
283 blink::WebFileUtilities
* RendererBlinkPlatformImpl::fileUtilities() {
284 if (!file_utilities_
) {
285 file_utilities_
.reset(new FileUtilities(thread_safe_sender_
.get()));
286 file_utilities_
->set_sandbox_enabled(sandboxEnabled());
288 return file_utilities_
.get();
291 blink::WebSandboxSupport
* RendererBlinkPlatformImpl::sandboxSupport() {
292 #if defined(OS_ANDROID) || defined(OS_WIN)
293 // These platforms do not require sandbox support.
296 return sandbox_support_
.get();
300 blink::WebCookieJar
* RendererBlinkPlatformImpl::cookieJar() {
301 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
305 blink::WebThemeEngine
* RendererBlinkPlatformImpl::themeEngine() {
306 blink::WebThemeEngine
* theme_engine
=
307 GetContentClient()->renderer()->OverrideThemeEngine();
310 return BlinkPlatformImpl::themeEngine();
313 bool RendererBlinkPlatformImpl::sandboxEnabled() {
314 // As explained in Platform.h, this function is used to decide
315 // whether to allow file system operations to come out of WebKit or not.
316 // Even if the sandbox is disabled, there's no reason why the code should
317 // act any differently...unless we're in single process mode. In which
318 // case, we have no other choice. Platform.h discourages using
319 // this switch unless absolutely necessary, so hopefully we won't end up
320 // with too many code paths being different in single-process mode.
321 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
322 switches::kSingleProcess
);
325 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
326 const char* canonical_url
,
328 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url
, length
);
331 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash
) {
332 return GetContentClient()->renderer()->IsLinkVisited(link_hash
);
335 void RendererBlinkPlatformImpl::createMessageChannel(
336 blink::WebMessagePortChannel
** channel1
,
337 blink::WebMessagePortChannel
** channel2
) {
338 WebMessagePortChannelImpl::CreatePair(
339 default_task_runner_
, channel1
, channel2
);
342 blink::WebPrescientNetworking
*
343 RendererBlinkPlatformImpl::prescientNetworking() {
344 return GetContentClient()->renderer()->GetPrescientNetworking();
347 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL
& url
,
351 // Let the browser know we generated cacheable metadata for this resource. The
352 // browser may cache it and return it on subsequent responses to speed
353 // the processing of this resource.
354 std::vector
<char> copy(data
, data
+ size
);
355 RenderThread::Get()->Send(new ViewHostMsg_DidGenerateCacheableMetadata(
356 url
, base::Time::FromInternalValue(response_time
), copy
));
359 WebString
RendererBlinkPlatformImpl::defaultLocale() {
360 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
363 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled
) {
365 // We should not get more enables than disables, but we want it to be a
366 // non-fatal error if it does happen.
367 DCHECK_GT(sudden_termination_disables_
, 0);
368 sudden_termination_disables_
= std::max(sudden_termination_disables_
- 1,
370 if (sudden_termination_disables_
!= 0)
373 sudden_termination_disables_
++;
374 if (sudden_termination_disables_
!= 1)
378 RenderThread
* thread
= RenderThread::Get();
379 if (thread
) // NULL in unittests.
380 thread
->Send(new ViewHostMsg_SuddenTerminationChanged(enabled
));
383 WebStorageNamespace
* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
384 return new WebStorageNamespaceImpl();
388 //------------------------------------------------------------------------------
390 WebIDBFactory
* RendererBlinkPlatformImpl::idbFactory() {
391 return web_idb_factory_
.get();
394 //------------------------------------------------------------------------------
396 blink::WebServiceWorkerCacheStorage
* RendererBlinkPlatformImpl::cacheStorage(
397 const WebString
& origin_identifier
) {
399 storage::GetOriginFromIdentifier(origin_identifier
.utf8());
400 return new WebServiceWorkerCacheStorageImpl(thread_safe_sender_
.get(),
404 //------------------------------------------------------------------------------
406 WebFileSystem
* RendererBlinkPlatformImpl::fileSystem() {
407 return WebFileSystemImpl::ThreadSpecificInstance(default_task_runner_
);
410 //------------------------------------------------------------------------------
412 WebMimeRegistry::SupportsType
413 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
414 const WebString
& mime_type
,
415 const WebString
& codecs
,
416 const WebString
& key_system
) {
417 const std::string mime_type_ascii
= ToASCIIOrEmpty(mime_type
);
418 // Not supporting the container is a flat-out no.
419 if (!media::IsSupportedMediaMimeType(mime_type_ascii
))
420 return IsNotSupported
;
422 if (!key_system
.isEmpty()) {
423 // Check whether the key system is supported with the mime_type and codecs.
425 // Chromium only supports ASCII parameters.
426 if (!base::IsStringASCII(key_system
))
427 return IsNotSupported
;
429 std::string key_system_ascii
=
430 media::GetUnprefixedKeySystemName(base::UTF16ToASCII(
431 base::StringPiece16(key_system
)));
432 std::vector
<std::string
> strict_codecs
;
433 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &strict_codecs
, true);
435 if (!media::PrefixedIsSupportedKeySystemWithMediaMimeType(
436 mime_type_ascii
, strict_codecs
, key_system_ascii
)) {
437 return IsNotSupported
;
440 // Continue processing the mime_type and codecs.
443 // Check list of strict codecs to see if it is supported.
444 if (media::IsStrictMediaMimeType(mime_type_ascii
)) {
445 // Check if the codecs are a perfect match.
446 std::vector
<std::string
> strict_codecs
;
447 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &strict_codecs
, false);
448 return static_cast<WebMimeRegistry::SupportsType
> (
449 media::IsSupportedStrictMediaMimeType(mime_type_ascii
, strict_codecs
));
452 // If we don't recognize the codec, it's possible we support it.
453 std::vector
<std::string
> parsed_codecs
;
454 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &parsed_codecs
, true);
455 if (!media::AreSupportedMediaCodecs(parsed_codecs
))
456 return MayBeSupported
;
458 // Otherwise we have a perfect match.
462 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
463 const blink::WebString
& mime_type
,
464 const WebString
& codecs
) {
465 const std::string mime_type_ascii
= ToASCIIOrEmpty(mime_type
);
466 std::vector
<std::string
> parsed_codec_ids
;
467 media::ParseCodecString(ToASCIIOrEmpty(codecs
), &parsed_codec_ids
, false);
468 if (mime_type_ascii
.empty())
470 return media::StreamParserFactory::IsTypeSupported(
471 mime_type_ascii
, parsed_codec_ids
);
474 WebString
RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
475 const WebString
& file_extension
) {
476 if (IsPluginProcess())
477 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension
);
479 // The sandbox restricts our access to the registry, so we need to proxy
480 // these calls over to the browser process.
481 std::string mime_type
;
482 RenderThread::Get()->Send(
483 new MimeRegistryMsg_GetMimeTypeFromExtension(
484 base::FilePath::FromUTF16Unsafe(file_extension
).value(), &mime_type
));
485 return base::ASCIIToUTF16(mime_type
);
488 WebString
RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
489 const WebString
& file_path
) {
490 if (IsPluginProcess())
491 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path
);
493 // The sandbox restricts our access to the registry, so we need to proxy
494 // these calls over to the browser process.
495 std::string mime_type
;
496 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
497 base::FilePath::FromUTF16Unsafe(file_path
),
499 return base::ASCIIToUTF16(mime_type
);
502 //------------------------------------------------------------------------------
504 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
505 const WebString
& path
,
506 WebFileInfo
& web_file_info
) {
507 base::File::Info file_info
;
508 base::File::Error status
= base::File::FILE_ERROR_MAX
;
509 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
510 base::FilePath::FromUTF16Unsafe(path
), &file_info
, &status
)) ||
511 status
!= base::File::FILE_OK
) {
514 FileInfoToWebFileInfo(file_info
, &web_file_info
);
515 web_file_info
.platformPath
= path
;
519 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
520 IPC::SyncMessage
* msg
) const {
521 base::TimeTicks begin
= base::TimeTicks::Now();
522 const bool success
= thread_safe_sender_
->Send(msg
);
523 base::TimeDelta delta
= base::TimeTicks::Now() - begin
;
524 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta
);
528 //------------------------------------------------------------------------------
530 #if defined(OS_MACOSX)
532 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont
* src_font
,
535 uint32 font_data_size
;
536 FontDescriptor
src_font_descriptor(src_font
);
537 base::SharedMemoryHandle font_data
;
538 if (!RenderThread::Get()->Send(new FrameHostMsg_LoadFont(
539 src_font_descriptor
, &font_data_size
, &font_data
, font_id
))) {
545 if (font_data_size
== 0 || font_data
== base::SharedMemory::NULLHandle() ||
547 LOG(ERROR
) << "Bad response from FrameHostMsg_LoadFont() for " <<
548 src_font_descriptor
.font_name
;
554 // TODO(jeremy): Need to call back into WebKit to make sure that the font
555 // isn't already activated, based on the font id. If it's already
556 // activated, don't reactivate it here - crbug.com/72727 .
558 return FontLoader::CGFontRefFromBuffer(font_data
, font_data_size
, out
);
561 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
563 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
564 blink::WebUChar32 character
,
565 const char* preferred_locale
,
566 blink::WebFallbackFont
* fallbackFont
) {
567 base::AutoLock
lock(unicode_font_families_mutex_
);
568 const std::map
<int32_t, blink::WebFallbackFont
>::const_iterator iter
=
569 unicode_font_families_
.find(character
);
570 if (iter
!= unicode_font_families_
.end()) {
571 fallbackFont
->name
= iter
->second
.name
;
572 fallbackFont
->filename
= iter
->second
.filename
;
573 fallbackFont
->fontconfigInterfaceId
= iter
->second
.fontconfigInterfaceId
;
574 fallbackFont
->ttcIndex
= iter
->second
.ttcIndex
;
575 fallbackFont
->isBold
= iter
->second
.isBold
;
576 fallbackFont
->isItalic
= iter
->second
.isItalic
;
580 GetFallbackFontForCharacter(character
, preferred_locale
, fallbackFont
);
581 unicode_font_families_
.insert(std::make_pair(character
, *fallbackFont
));
584 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
587 blink::WebFontRenderStyle
* out
) {
588 GetRenderStyleForStrike(family
, sizeAndStyle
, out
);
593 //------------------------------------------------------------------------------
595 Platform::FileHandle
RendererBlinkPlatformImpl::databaseOpenFile(
596 const WebString
& vfs_file_name
,
598 return DatabaseUtil::DatabaseOpenFile(
599 vfs_file_name
, desired_flags
, sync_message_filter_
.get());
602 int RendererBlinkPlatformImpl::databaseDeleteFile(
603 const WebString
& vfs_file_name
,
605 return DatabaseUtil::DatabaseDeleteFile(
606 vfs_file_name
, sync_dir
, sync_message_filter_
.get());
609 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
610 const WebString
& vfs_file_name
) {
611 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name
,
612 sync_message_filter_
.get());
615 long long RendererBlinkPlatformImpl::databaseGetFileSize(
616 const WebString
& vfs_file_name
) {
617 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name
,
618 sync_message_filter_
.get());
621 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
622 const WebString
& origin_identifier
) {
623 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier
,
624 sync_message_filter_
.get());
627 bool RendererBlinkPlatformImpl::databaseSetFileSize(
628 const WebString
& vfs_file_name
, long long size
) {
629 return DatabaseUtil::DatabaseSetFileSize(
630 vfs_file_name
, size
, sync_message_filter_
.get());
633 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
634 #if defined(OS_ANDROID)
635 SynchronousCompositorFactory
* factory
=
636 SynchronousCompositorFactory::GetInstance();
637 if (factory
&& factory
->OverrideWithFactory()) {
638 return factory
->GetGPUInfo().SupportsAccelerated2dCanvas();
642 RenderThreadImpl
* thread
= RenderThreadImpl::current();
643 GpuChannelHost
* host
= thread
->EstablishGpuChannelSync(
644 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D
);
648 return host
->gpu_info().SupportsAccelerated2dCanvas();
651 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
652 RenderThreadImpl
* thread
= RenderThreadImpl::current();
653 // thread can be NULL in tests.
654 return thread
&& thread
->compositor_task_runner().get();
657 bool RendererBlinkPlatformImpl::isThreadedAnimationEnabled() {
658 RenderThreadImpl
* thread
= RenderThreadImpl::current();
659 return thread
? thread
->IsThreadedAnimationEnabled() : true;
662 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
663 RenderThreadImpl
* thread
= RenderThreadImpl::current();
664 return thread
->GetAudioHardwareConfig()->GetOutputSampleRate();
667 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
668 RenderThreadImpl
* thread
= RenderThreadImpl::current();
669 return thread
->GetAudioHardwareConfig()->GetOutputBufferSize();
672 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
673 RenderThreadImpl
* thread
= RenderThreadImpl::current();
674 return thread
->GetAudioHardwareConfig()->GetOutputChannels();
677 WebDatabaseObserver
* RendererBlinkPlatformImpl::databaseObserver() {
678 return web_database_observer_impl_
.get();
681 WebAudioDevice
* RendererBlinkPlatformImpl::createAudioDevice(
683 unsigned input_channels
,
686 WebAudioDevice::RenderCallback
* callback
,
687 const blink::WebString
& input_device_id
) {
688 // Use a mock for testing.
689 blink::WebAudioDevice
* mock_device
=
690 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate
);
694 // The |channels| does not exactly identify the channel layout of the
695 // device. The switch statement below assigns a best guess to the channel
696 // layout based on number of channels.
697 media::ChannelLayout layout
= media::CHANNEL_LAYOUT_UNSUPPORTED
;
700 layout
= media::CHANNEL_LAYOUT_MONO
;
703 layout
= media::CHANNEL_LAYOUT_STEREO
;
706 layout
= media::CHANNEL_LAYOUT_2_1
;
709 layout
= media::CHANNEL_LAYOUT_4_0
;
712 layout
= media::CHANNEL_LAYOUT_5_0
;
715 layout
= media::CHANNEL_LAYOUT_5_1
;
718 layout
= media::CHANNEL_LAYOUT_7_0
;
721 layout
= media::CHANNEL_LAYOUT_7_1
;
724 // If the layout is not supported (more than 9 channels), falls back to
726 layout
= media::CHANNEL_LAYOUT_DISCRETE
;
730 if (input_device_id
.isNull() ||
731 !base::StringToInt(base::UTF16ToUTF8(
732 base::StringPiece16(input_device_id
)), &session_id
)) {
733 if (input_channels
> 0)
734 DLOG(WARNING
) << "createAudioDevice(): request for audio input ignored";
739 // For CHANNEL_LAYOUT_DISCRETE, pass the explicit channel count along with
740 // the channel layout when creating an |AudioParameters| object.
741 media::AudioParameters
params(media::AudioParameters::AUDIO_PCM_LOW_LATENCY
,
742 layout
, static_cast<int>(sample_rate
), 16,
744 params
.set_channels_for_discrete(channels
);
746 return new RendererWebAudioDeviceImpl(params
, callback
, session_id
);
749 #if defined(OS_ANDROID)
750 bool RendererBlinkPlatformImpl::loadAudioResource(
751 blink::WebAudioBus
* destination_bus
,
752 const char* audio_file_data
,
754 return DecodeAudioFileData(destination_bus
,
757 thread_safe_sender_
);
760 bool RendererBlinkPlatformImpl::loadAudioResource(
761 blink::WebAudioBus
* destination_bus
,
762 const char* audio_file_data
,
764 return DecodeAudioFileData(
765 destination_bus
, audio_file_data
, data_size
);
767 #endif // defined(OS_ANDROID)
769 //------------------------------------------------------------------------------
771 blink::WebMIDIAccessor
* RendererBlinkPlatformImpl::createMIDIAccessor(
772 blink::WebMIDIAccessorClient
* client
) {
773 blink::WebMIDIAccessor
* accessor
=
774 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client
);
778 return new RendererWebMIDIAccessorImpl(client
);
781 void RendererBlinkPlatformImpl::getPluginList(
783 blink::WebPluginListBuilder
* builder
) {
784 #if defined(ENABLE_PLUGINS)
785 std::vector
<WebPluginInfo
> plugins
;
786 if (!plugin_refresh_allowed_
)
788 RenderThread::Get()->Send(new FrameHostMsg_GetPlugins(refresh
, &plugins
));
789 for (const WebPluginInfo
& plugin
: plugins
) {
791 plugin
.name
, plugin
.desc
,
792 plugin
.path
.BaseName().AsUTF16Unsafe());
794 for (const WebPluginMimeType
& mime_type
: plugin
.mime_types
) {
795 builder
->addMediaTypeToLastPlugin(
796 WebString::fromUTF8(mime_type
.mime_type
), mime_type
.description
);
798 for (const auto& extension
: mime_type
.file_extensions
) {
799 builder
->addFileExtensionToLastMediaType(
800 WebString::fromUTF8(extension
));
807 //------------------------------------------------------------------------------
809 blink::WebPublicSuffixList
* RendererBlinkPlatformImpl::publicSuffixList() {
810 return &public_suffix_list_
;
813 //------------------------------------------------------------------------------
815 blink::WebString
RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
816 unsigned key_size_index
,
817 const blink::WebString
& challenge
,
818 const blink::WebURL
& url
) {
819 std::string signed_public_key
;
820 RenderThread::Get()->Send(new FrameHostMsg_Keygen(
821 static_cast<uint32
>(key_size_index
),
824 &signed_public_key
));
825 return WebString::fromUTF8(signed_public_key
);
828 //------------------------------------------------------------------------------
830 void RendererBlinkPlatformImpl::screenColorProfile(
831 WebVector
<char>* to_profile
) {
833 // On Windows screen color profile is only available in the browser.
834 std::vector
<char> profile
;
835 // This Send() can be called from any impl-side thread. Use a thread
836 // safe send to avoid crashing trying to access RenderThread::Get(),
837 // which is not accessible from arbitrary threads.
838 thread_safe_sender_
->Send(
839 new ViewHostMsg_GetMonitorColorProfile(&profile
));
840 *to_profile
= profile
;
842 // On other platforms, the primary monitor color profile can be read
844 gfx::ColorProfile profile
;
845 *to_profile
= profile
.profile();
849 //------------------------------------------------------------------------------
851 blink::WebScrollbarBehavior
* RendererBlinkPlatformImpl::scrollbarBehavior() {
852 return web_scrollbar_behavior_
.get();
855 //------------------------------------------------------------------------------
857 WebBlobRegistry
* RendererBlinkPlatformImpl::blobRegistry() {
858 // blob_registry_ can be NULL when running some tests.
859 return blob_registry_
.get();
862 //------------------------------------------------------------------------------
864 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads
& gamepads
) {
865 PlatformEventObserverBase
* observer
=
866 platform_event_observers_
.Lookup(blink::WebPlatformEventGamepad
);
869 static_cast<RendererGamepadProvider
*>(observer
)->SampleGamepads(gamepads
);
872 //------------------------------------------------------------------------------
874 WebRTCPeerConnectionHandler
*
875 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
876 WebRTCPeerConnectionHandlerClient
* client
) {
877 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
878 DCHECK(render_thread
);
882 #if defined(ENABLE_WEBRTC)
883 WebRTCPeerConnectionHandler
* peer_connection_handler
=
884 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
886 if (peer_connection_handler
)
887 return peer_connection_handler
;
889 PeerConnectionDependencyFactory
* rtc_dependency_factory
=
890 render_thread
->GetPeerConnectionDependencyFactory();
891 return rtc_dependency_factory
->CreateRTCPeerConnectionHandler(client
);
894 #endif // defined(ENABLE_WEBRTC)
897 //------------------------------------------------------------------------------
899 WebMediaStreamCenter
* RendererBlinkPlatformImpl::createMediaStreamCenter(
900 WebMediaStreamCenterClient
* client
) {
901 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
902 DCHECK(render_thread
);
905 return render_thread
->CreateMediaStreamCenter(client
);
909 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable
) {
910 bool was_enabled
= g_sandbox_enabled
;
911 g_sandbox_enabled
= enable
;
915 //------------------------------------------------------------------------------
917 blink::WebSpeechSynthesizer
* RendererBlinkPlatformImpl::createSpeechSynthesizer(
918 blink::WebSpeechSynthesizerClient
* client
) {
919 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client
);
922 //------------------------------------------------------------------------------
924 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
925 size_t* private_bytes
,
926 size_t* shared_bytes
) {
927 content::RenderThread::Get()->Send(
928 new ViewHostMsg_GetProcessMemorySizes(private_bytes
, shared_bytes
));
932 //------------------------------------------------------------------------------
934 blink::WebGraphicsContext3D
*
935 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
936 const blink::WebGraphicsContext3D::Attributes
& attributes
) {
937 return createOffscreenGraphicsContext3D(attributes
, NULL
);
940 blink::WebGraphicsContext3D
*
941 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
942 const blink::WebGraphicsContext3D::Attributes
& attributes
,
943 blink::WebGraphicsContext3D
* share_context
) {
944 return createOffscreenGraphicsContext3D(attributes
, share_context
, NULL
);
947 blink::WebGraphicsContext3D
*
948 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
949 const blink::WebGraphicsContext3D::Attributes
& attributes
,
950 blink::WebGraphicsContext3D
* share_context
,
951 blink::WebGLInfo
* gl_info
) {
952 if (!RenderThreadImpl::current())
955 #if defined(OS_ANDROID)
956 SynchronousCompositorFactory
* factory
=
957 SynchronousCompositorFactory::GetInstance();
958 if (factory
&& factory
->OverrideWithFactory()) {
959 scoped_ptr
<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl
>
961 factory
->CreateOffscreenGraphicsContext3D(attributes
));
962 if (!in_process_context
|| !in_process_context
->InitializeOnCurrentThread())
964 return in_process_context
.release();
968 scoped_refptr
<GpuChannelHost
> gpu_channel_host(
969 RenderThreadImpl::current()->EstablishGpuChannelSync(
970 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
972 if (gpu_channel_host
.get() && gl_info
) {
973 const gpu::GPUInfo
& gpu_info
= gpu_channel_host
->gpu_info();
974 switch (gpu_info
.context_info_state
) {
975 case gpu::kCollectInfoSuccess
:
976 case gpu::kCollectInfoNonFatalFailure
:
977 gl_info
->vendorInfo
.assign(
978 blink::WebString::fromUTF8(gpu_info
.gl_vendor
));
979 gl_info
->rendererInfo
.assign(
980 blink::WebString::fromUTF8(gpu_info
.gl_renderer
));
981 gl_info
->driverVersion
.assign(
982 blink::WebString::fromUTF8(gpu_info
.driver_version
));
983 gl_info
->vendorId
= gpu_info
.gpu
.vendor_id
;
984 gl_info
->deviceId
= gpu_info
.gpu
.device_id
;
986 case gpu::kCollectInfoFatalFailure
:
987 case gpu::kCollectInfoNone
:
988 gl_info
->contextInfoCollectionFailure
.assign(blink::WebString::fromUTF8(
989 "GPUInfoCollectionFailure: GPU initialization Failed. GPU "
990 "Info not Collected."));
997 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits
;
998 bool lose_context_when_out_of_memory
= false;
999 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
> context(
1000 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1001 gpu_channel_host
.get(),
1003 lose_context_when_out_of_memory
,
1004 GURL(attributes
.topDocumentURL
),
1006 static_cast<WebGraphicsContext3DCommandBufferImpl
*>(share_context
)));
1008 // Most likely the GPU process exited and the attempt to reconnect to it
1009 // failed. Need to try to restore the context again later.
1010 if (!context
|| !context
->InitializeOnCurrentThread())
1012 return context
.release();
1015 //------------------------------------------------------------------------------
1017 blink::WebGraphicsContext3DProvider
*
1018 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
1019 scoped_refptr
<cc_blink::ContextProviderWebContext
> provider
=
1020 RenderThreadImpl::current()->SharedMainThreadContextProvider();
1021 if (!provider
.get())
1023 return new WebGraphicsContext3DProviderImpl(provider
);
1026 //------------------------------------------------------------------------------
1028 blink::WebCompositorSupport
* RendererBlinkPlatformImpl::compositorSupport() {
1029 return &compositor_support_
;
1032 //------------------------------------------------------------------------------
1034 blink::WebString
RendererBlinkPlatformImpl::convertIDNToUnicode(
1035 const blink::WebString
& host
,
1036 const blink::WebString
& languages
) {
1037 return url_formatter::IDNToUnicode(host
.utf8(), languages
.utf8());
1040 //------------------------------------------------------------------------------
1042 void RendererBlinkPlatformImpl::recordRappor(const char* metric
,
1043 const blink::WebString
& sample
) {
1044 GetContentClient()->renderer()->RecordRappor(metric
, sample
.utf8());
1047 void RendererBlinkPlatformImpl::recordRapporURL(const char* metric
,
1048 const blink::WebURL
& url
) {
1049 GetContentClient()->renderer()->RecordRapporURL(metric
, url
);
1052 //------------------------------------------------------------------------------
1055 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data
) {
1056 g_test_device_light_data
= data
;
1059 //------------------------------------------------------------------------------
1062 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1063 const blink::WebDeviceMotionData
& data
) {
1064 g_test_device_motion_data
.Get() = data
;
1067 //------------------------------------------------------------------------------
1070 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1071 const blink::WebDeviceOrientationData
& data
) {
1072 g_test_device_orientation_data
.Get() = data
;
1075 //------------------------------------------------------------------------------
1077 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds
) {
1078 GetConnectedVibrationManagerService()->Vibrate(
1079 base::checked_cast
<int64
>(milliseconds
));
1080 vibration_manager_
.reset();
1083 void RendererBlinkPlatformImpl::cancelVibration() {
1084 GetConnectedVibrationManagerService()->Cancel();
1085 vibration_manager_
.reset();
1088 device::VibrationManagerPtr
&
1089 RendererBlinkPlatformImpl::GetConnectedVibrationManagerService() {
1090 if (!vibration_manager_
) {
1091 RenderThread::Get()->GetServiceRegistry()->ConnectToRemoteService(
1092 mojo::GetProxy(&vibration_manager_
));
1094 return vibration_manager_
;
1097 //------------------------------------------------------------------------------
1100 PlatformEventObserverBase
*
1101 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1102 blink::WebPlatformEventType type
) {
1103 RenderThread
* thread
= RenderThreadImpl::current();
1105 // When running layout tests, those observers should not listen to the actual
1106 // hardware changes. In order to make that happen, they will receive a null
1108 if (thread
&& RenderThreadImpl::current()->layout_test_mode())
1112 case blink::WebPlatformEventDeviceMotion
:
1113 return new DeviceMotionEventPump(thread
);
1114 case blink::WebPlatformEventDeviceOrientation
:
1115 return new DeviceOrientationEventPump(thread
);
1116 case blink::WebPlatformEventDeviceLight
:
1117 return new DeviceLightEventPump(thread
);
1118 case blink::WebPlatformEventGamepad
:
1119 return new GamepadSharedMemoryReader(thread
);
1120 case blink::WebPlatformEventScreenOrientation
:
1121 return new ScreenOrientationObserver();
1123 // A default statement is required to prevent compilation errors when
1124 // Blink adds a new type.
1125 DVLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1132 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1133 blink::WebPlatformEventType type
,
1134 scoped_ptr
<PlatformEventObserverBase
> observer
) {
1135 DCHECK(type
!= blink::WebPlatformEventBattery
);
1137 if (platform_event_observers_
.Lookup(type
))
1138 platform_event_observers_
.Remove(type
);
1139 platform_event_observers_
.AddWithID(observer
.release(), type
);
1142 void RendererBlinkPlatformImpl::startListening(
1143 blink::WebPlatformEventType type
,
1144 blink::WebPlatformEventListener
* listener
) {
1145 if (type
== blink::WebPlatformEventBattery
) {
1146 if (RenderThreadImpl::current() &&
1147 RenderThreadImpl::current()->layout_test_mode()) {
1148 g_test_battery_status_listener
=
1149 static_cast<blink::WebBatteryStatusListener
*>(listener
);
1151 battery_status_dispatcher_
.reset(new BatteryStatusDispatcher(
1152 static_cast<blink::WebBatteryStatusListener
*>(listener
)));
1157 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1159 observer
= CreatePlatformEventObserverFromType(type
);
1162 platform_event_observers_
.AddWithID(observer
, static_cast<int32
>(type
));
1164 observer
->Start(listener
);
1166 // Device events (motion, orientation and light) expect to get an event fired
1167 // as soon as a listener is registered if a fake data was passed before.
1168 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1169 // using this broken pattern.
1170 if (RenderThreadImpl::current() &&
1171 RenderThreadImpl::current()->layout_test_mode() &&
1172 (type
== blink::WebPlatformEventDeviceMotion
||
1173 type
== blink::WebPlatformEventDeviceOrientation
||
1174 type
== blink::WebPlatformEventDeviceLight
)) {
1175 SendFakeDeviceEventDataForTesting(type
);
1179 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1180 blink::WebPlatformEventType type
) {
1181 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1187 case blink::WebPlatformEventDeviceMotion
:
1188 if (!(g_test_device_motion_data
== 0))
1189 data
= &g_test_device_motion_data
.Get();
1191 case blink::WebPlatformEventDeviceOrientation
:
1192 if (!(g_test_device_orientation_data
== 0))
1193 data
= &g_test_device_orientation_data
.Get();
1195 case blink::WebPlatformEventDeviceLight
:
1196 if (g_test_device_light_data
>= 0)
1197 data
= &g_test_device_light_data
;
1207 base::ThreadTaskRunnerHandle::Get()->PostTask(
1208 FROM_HERE
, base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting
,
1209 base::Unretained(observer
), data
));
1212 void RendererBlinkPlatformImpl::stopListening(
1213 blink::WebPlatformEventType type
) {
1214 if (type
== blink::WebPlatformEventBattery
) {
1215 g_test_battery_status_listener
= nullptr;
1216 battery_status_dispatcher_
.reset();
1220 PlatformEventObserverBase
* observer
= platform_event_observers_
.Lookup(type
);
1226 //------------------------------------------------------------------------------
1228 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1229 const blink::WebURL
& storage_partition
,
1230 blink::WebStorageQuotaType type
,
1231 blink::WebStorageQuotaCallbacks callbacks
) {
1232 if (!thread_safe_sender_
.get() || !quota_message_filter_
.get())
1234 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_
.get(),
1235 quota_message_filter_
.get())
1236 ->QueryStorageUsageAndQuota(
1238 static_cast<storage::StorageType
>(type
),
1239 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
1242 //------------------------------------------------------------------------------
1244 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1245 const blink::WebBatteryStatus
& status
) {
1246 if (!g_test_battery_status_listener
)
1248 g_test_battery_status_listener
->updateBatteryStatus(status
);
1251 } // namespace content