Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / content / renderer / renderer_webkitplatformsupport_impl.cc
blobdd0c3c12bf44d6b6a8be0b4f6e05e99786129b7d
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_webkitplatformsupport_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 "content/child/database_util.h"
18 #include "content/child/file_info_util.h"
19 #include "content/child/fileapi/webfilesystem_impl.h"
20 #include "content/child/indexed_db/webidbfactory_impl.h"
21 #include "content/child/npapi/npobject_util.h"
22 #include "content/child/quota_dispatcher.h"
23 #include "content/child/quota_message_filter.h"
24 #include "content/child/simple_webmimeregistry_impl.h"
25 #include "content/child/thread_safe_sender.h"
26 #include "content/child/web_database_observer_impl.h"
27 #include "content/child/webblobregistry_impl.h"
28 #include "content/child/webfileutilities_impl.h"
29 #include "content/child/webmessageportchannel_impl.h"
30 #include "content/common/file_utilities_messages.h"
31 #include "content/common/gpu/client/context_provider_command_buffer.h"
32 #include "content/common/gpu/client/gpu_channel_host.h"
33 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
34 #include "content/common/gpu/gpu_process_launch_causes.h"
35 #include "content/common/mime_registry_messages.h"
36 #include "content/common/view_messages.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/webplugininfo.h"
39 #include "content/public/renderer/content_renderer_client.h"
40 #include "content/renderer/battery_status/battery_status_dispatcher.h"
41 #include "content/renderer/device_sensors/device_light_event_pump.h"
42 #include "content/renderer/device_sensors/device_motion_event_pump.h"
43 #include "content/renderer/device_sensors/device_orientation_event_pump.h"
44 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
45 #include "content/renderer/gamepad_shared_memory_reader.h"
46 #include "content/renderer/media/audio_decoder.h"
47 #include "content/renderer/media/crypto/key_systems.h"
48 #include "content/renderer/media/renderer_webaudiodevice_impl.h"
49 #include "content/renderer/media/renderer_webmidiaccessor_impl.h"
50 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_clipboard_client.h"
53 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
54 #include "content/renderer/webclipboard_impl.h"
55 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
56 #include "content/renderer/webpublicsuffixlist_impl.h"
57 #include "gpu/config/gpu_info.h"
58 #include "ipc/ipc_sync_message_filter.h"
59 #include "media/audio/audio_output_device.h"
60 #include "media/base/audio_hardware_config.h"
61 #include "media/filters/stream_parser_factory.h"
62 #include "net/base/mime_util.h"
63 #include "net/base/net_util.h"
64 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
65 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
66 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
67 #include "third_party/WebKit/public/platform/WebDeviceMotionListener.h"
68 #include "third_party/WebKit/public/platform/WebDeviceOrientationListener.h"
69 #include "third_party/WebKit/public/platform/WebFileInfo.h"
70 #include "third_party/WebKit/public/platform/WebGamepads.h"
71 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
72 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
73 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
74 #include "third_party/WebKit/public/platform/WebURL.h"
75 #include "third_party/WebKit/public/platform/WebVector.h"
76 #include "ui/gfx/color_profile.h"
77 #include "url/gurl.h"
78 #include "webkit/common/gpu/context_provider_web_context.h"
79 #include "webkit/common/quota/quota_types.h"
81 #if defined(OS_ANDROID)
82 #include "content/renderer/android/synchronous_compositor_factory.h"
83 #include "content/renderer/media/android/audio_decoder_android.h"
84 #endif
86 #if defined(OS_MACOSX)
87 #include "content/common/mac/font_descriptor.h"
88 #include "content/common/mac/font_loader.h"
89 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
90 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
91 #endif
93 #if defined(OS_POSIX)
94 #include "base/file_descriptor_posix.h"
95 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
96 #include <map>
97 #include <string>
99 #include "base/synchronization/lock.h"
100 #include "content/common/child_process_sandbox_support_impl_linux.h"
101 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
102 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
103 #include "third_party/icu/source/common/unicode/utf16.h"
104 #endif
105 #endif
107 #if defined(OS_WIN)
108 #include "content/common/child_process_messages.h"
109 #include "third_party/WebKit/public/platform/win/WebSandboxSupport.h"
110 #endif
112 #if defined(USE_AURA)
113 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
114 #elif !defined(OS_MACOSX)
115 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
116 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
117 #endif
119 #if defined(ENABLE_WEBRTC)
120 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
121 #endif
123 using blink::Platform;
124 using blink::WebAudioDevice;
125 using blink::WebBlobRegistry;
126 using blink::WebDatabaseObserver;
127 using blink::WebFileInfo;
128 using blink::WebFileSystem;
129 using blink::WebGamepad;
130 using blink::WebGamepads;
131 using blink::WebIDBFactory;
132 using blink::WebMIDIAccessor;
133 using blink::WebMediaStreamCenter;
134 using blink::WebMediaStreamCenterClient;
135 using blink::WebMimeRegistry;
136 using blink::WebRTCPeerConnectionHandler;
137 using blink::WebRTCPeerConnectionHandlerClient;
138 using blink::WebStorageNamespace;
139 using blink::WebString;
140 using blink::WebURL;
141 using blink::WebVector;
143 namespace content {
145 namespace {
147 bool g_sandbox_enabled = true;
148 double g_test_device_light_data = -1;
149 base::LazyInstance<blink::WebDeviceMotionData>::Leaky
150 g_test_device_motion_data = LAZY_INSTANCE_INITIALIZER;
151 base::LazyInstance<blink::WebDeviceOrientationData>::Leaky
152 g_test_device_orientation_data = LAZY_INSTANCE_INITIALIZER;
154 } // namespace
156 //------------------------------------------------------------------------------
158 class RendererWebKitPlatformSupportImpl::MimeRegistry
159 : public SimpleWebMimeRegistryImpl {
160 public:
161 virtual blink::WebMimeRegistry::SupportsType supportsMediaMIMEType(
162 const blink::WebString& mime_type,
163 const blink::WebString& codecs,
164 const blink::WebString& key_system);
165 virtual bool supportsMediaSourceMIMEType(const blink::WebString& mime_type,
166 const blink::WebString& codecs);
167 virtual bool supportsEncryptedMediaMIMEType(const WebString& key_system,
168 const WebString& mime_type,
169 const WebString& codecs) OVERRIDE;
170 virtual blink::WebString mimeTypeForExtension(
171 const blink::WebString& file_extension);
172 virtual blink::WebString mimeTypeFromFile(
173 const blink::WebString& file_path);
176 class RendererWebKitPlatformSupportImpl::FileUtilities
177 : public WebFileUtilitiesImpl {
178 public:
179 explicit FileUtilities(ThreadSafeSender* sender)
180 : thread_safe_sender_(sender) {}
181 virtual bool getFileInfo(const WebString& path, WebFileInfo& result);
182 private:
183 bool SendSyncMessageFromAnyThread(IPC::SyncMessage* msg) const;
184 scoped_refptr<ThreadSafeSender> thread_safe_sender_;
187 #if defined(OS_ANDROID)
188 // WebKit doesn't use WebSandboxSupport on android so we don't need to
189 // implement anything here.
190 class RendererWebKitPlatformSupportImpl::SandboxSupport {
192 #else
193 class RendererWebKitPlatformSupportImpl::SandboxSupport
194 : public blink::WebSandboxSupport {
195 public:
196 virtual ~SandboxSupport() {}
198 #if defined(OS_WIN)
199 virtual bool ensureFontLoaded(HFONT);
200 #elif defined(OS_MACOSX)
201 virtual bool loadFont(
202 NSFont* src_font,
203 CGFontRef* container,
204 uint32* font_id);
205 #elif defined(OS_POSIX)
206 virtual void getFallbackFontForCharacter(
207 blink::WebUChar32 character,
208 const char* preferred_locale,
209 blink::WebFallbackFont* fallbackFont);
210 virtual void getRenderStyleForStrike(
211 const char* family, int sizeAndStyle, blink::WebFontRenderStyle* out);
213 private:
214 // WebKit likes to ask us for the correct font family to use for a set of
215 // unicode code points. It needs this information frequently so we cache it
216 // here.
217 base::Lock unicode_font_families_mutex_;
218 std::map<int32_t, blink::WebFallbackFont> unicode_font_families_;
219 #endif
221 #endif // defined(OS_ANDROID)
223 //------------------------------------------------------------------------------
225 RendererWebKitPlatformSupportImpl::RendererWebKitPlatformSupportImpl()
226 : clipboard_client_(new RendererClipboardClient),
227 clipboard_(new WebClipboardImpl(clipboard_client_.get())),
228 mime_registry_(new RendererWebKitPlatformSupportImpl::MimeRegistry),
229 sudden_termination_disables_(0),
230 plugin_refresh_allowed_(true),
231 child_thread_loop_(base::MessageLoopProxy::current()),
232 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl) {
233 if (g_sandbox_enabled && sandboxEnabled()) {
234 sandbox_support_.reset(
235 new RendererWebKitPlatformSupportImpl::SandboxSupport);
236 } else {
237 DVLOG(1) << "Disabling sandbox support for testing.";
240 // ChildThread may not exist in some tests.
241 if (ChildThread::current()) {
242 sync_message_filter_ = ChildThread::current()->sync_message_filter();
243 thread_safe_sender_ = ChildThread::current()->thread_safe_sender();
244 quota_message_filter_ = ChildThread::current()->quota_message_filter();
245 blob_registry_.reset(new WebBlobRegistryImpl(thread_safe_sender_.get()));
246 web_idb_factory_.reset(new WebIDBFactoryImpl(thread_safe_sender_.get()));
247 web_database_observer_impl_.reset(
248 new WebDatabaseObserverImpl(sync_message_filter_.get()));
252 RendererWebKitPlatformSupportImpl::~RendererWebKitPlatformSupportImpl() {
253 WebFileSystemImpl::DeleteThreadSpecificInstance();
256 //------------------------------------------------------------------------------
258 blink::WebClipboard* RendererWebKitPlatformSupportImpl::clipboard() {
259 blink::WebClipboard* clipboard =
260 GetContentClient()->renderer()->OverrideWebClipboard();
261 if (clipboard)
262 return clipboard;
263 return clipboard_.get();
266 blink::WebMimeRegistry* RendererWebKitPlatformSupportImpl::mimeRegistry() {
267 return mime_registry_.get();
270 blink::WebFileUtilities*
271 RendererWebKitPlatformSupportImpl::fileUtilities() {
272 if (!file_utilities_) {
273 file_utilities_.reset(new FileUtilities(thread_safe_sender_.get()));
274 file_utilities_->set_sandbox_enabled(sandboxEnabled());
276 return file_utilities_.get();
279 blink::WebSandboxSupport* RendererWebKitPlatformSupportImpl::sandboxSupport() {
280 #if defined(OS_ANDROID)
281 // WebKit doesn't use WebSandboxSupport on android.
282 return NULL;
283 #else
284 return sandbox_support_.get();
285 #endif
288 blink::WebCookieJar* RendererWebKitPlatformSupportImpl::cookieJar() {
289 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
290 return NULL;
293 blink::WebThemeEngine* RendererWebKitPlatformSupportImpl::themeEngine() {
294 blink::WebThemeEngine* theme_engine =
295 GetContentClient()->renderer()->OverrideThemeEngine();
296 if (theme_engine)
297 return theme_engine;
298 return BlinkPlatformImpl::themeEngine();
301 bool RendererWebKitPlatformSupportImpl::sandboxEnabled() {
302 // As explained in Platform.h, this function is used to decide
303 // whether to allow file system operations to come out of WebKit or not.
304 // Even if the sandbox is disabled, there's no reason why the code should
305 // act any differently...unless we're in single process mode. In which
306 // case, we have no other choice. Platform.h discourages using
307 // this switch unless absolutely necessary, so hopefully we won't end up
308 // with too many code paths being different in single-process mode.
309 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);
312 unsigned long long RendererWebKitPlatformSupportImpl::visitedLinkHash(
313 const char* canonical_url,
314 size_t length) {
315 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url, length);
318 bool RendererWebKitPlatformSupportImpl::isLinkVisited(
319 unsigned long long link_hash) {
320 return GetContentClient()->renderer()->IsLinkVisited(link_hash);
323 void RendererWebKitPlatformSupportImpl::createMessageChannel(
324 blink::WebMessagePortChannel** channel1,
325 blink::WebMessagePortChannel** channel2) {
326 WebMessagePortChannelImpl::CreatePair(
327 child_thread_loop_.get(), channel1, channel2);
330 blink::WebPrescientNetworking*
331 RendererWebKitPlatformSupportImpl::prescientNetworking() {
332 return GetContentClient()->renderer()->GetPrescientNetworking();
335 void RendererWebKitPlatformSupportImpl::cacheMetadata(
336 const blink::WebURL& url,
337 double response_time,
338 const char* data,
339 size_t size) {
340 // Let the browser know we generated cacheable metadata for this resource. The
341 // browser may cache it and return it on subsequent responses to speed
342 // the processing of this resource.
343 std::vector<char> copy(data, data + size);
344 RenderThread::Get()->Send(
345 new ViewHostMsg_DidGenerateCacheableMetadata(url, response_time, copy));
348 WebString RendererWebKitPlatformSupportImpl::defaultLocale() {
349 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
352 void RendererWebKitPlatformSupportImpl::suddenTerminationChanged(bool enabled) {
353 if (enabled) {
354 // We should not get more enables than disables, but we want it to be a
355 // non-fatal error if it does happen.
356 DCHECK_GT(sudden_termination_disables_, 0);
357 sudden_termination_disables_ = std::max(sudden_termination_disables_ - 1,
359 if (sudden_termination_disables_ != 0)
360 return;
361 } else {
362 sudden_termination_disables_++;
363 if (sudden_termination_disables_ != 1)
364 return;
367 RenderThread* thread = RenderThread::Get();
368 if (thread) // NULL in unittests.
369 thread->Send(new ViewHostMsg_SuddenTerminationChanged(enabled));
372 WebStorageNamespace*
373 RendererWebKitPlatformSupportImpl::createLocalStorageNamespace() {
374 return new WebStorageNamespaceImpl();
378 //------------------------------------------------------------------------------
380 WebIDBFactory* RendererWebKitPlatformSupportImpl::idbFactory() {
381 return web_idb_factory_.get();
384 //------------------------------------------------------------------------------
386 WebFileSystem* RendererWebKitPlatformSupportImpl::fileSystem() {
387 return WebFileSystemImpl::ThreadSpecificInstance(child_thread_loop_.get());
390 //------------------------------------------------------------------------------
392 WebMimeRegistry::SupportsType
393 RendererWebKitPlatformSupportImpl::MimeRegistry::supportsMediaMIMEType(
394 const WebString& mime_type,
395 const WebString& codecs,
396 const WebString& key_system) {
397 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
398 // Not supporting the container is a flat-out no.
399 if (!net::IsSupportedMediaMimeType(mime_type_ascii))
400 return IsNotSupported;
402 if (!key_system.isEmpty()) {
403 // Check whether the key system is supported with the mime_type and codecs.
405 // Chromium only supports ASCII parameters.
406 if (!base::IsStringASCII(key_system))
407 return IsNotSupported;
409 std::string key_system_ascii =
410 GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system));
411 std::vector<std::string> strict_codecs;
412 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, true);
414 if (!IsSupportedKeySystemWithMediaMimeType(
415 mime_type_ascii, strict_codecs, key_system_ascii)) {
416 return IsNotSupported;
419 // Continue processing the mime_type and codecs.
422 // Check list of strict codecs to see if it is supported.
423 if (net::IsStrictMediaMimeType(mime_type_ascii)) {
424 // Check if the codecs are a perfect match.
425 std::vector<std::string> strict_codecs;
426 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
427 return static_cast<WebMimeRegistry::SupportsType> (
428 net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
431 // If we don't recognize the codec, it's possible we support it.
432 std::vector<std::string> parsed_codecs;
433 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
434 if (!net::AreSupportedMediaCodecs(parsed_codecs))
435 return MayBeSupported;
437 // Otherwise we have a perfect match.
438 return IsSupported;
441 bool
442 RendererWebKitPlatformSupportImpl::MimeRegistry::supportsMediaSourceMIMEType(
443 const blink::WebString& mime_type,
444 const WebString& codecs) {
445 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
446 std::vector<std::string> parsed_codec_ids;
447 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
448 if (mime_type_ascii.empty())
449 return false;
450 return media::StreamParserFactory::IsTypeSupported(
451 mime_type_ascii, parsed_codec_ids);
454 bool
455 RendererWebKitPlatformSupportImpl::MimeRegistry::supportsEncryptedMediaMIMEType(
456 const WebString& key_system,
457 const WebString& mime_type,
458 const WebString& codecs) {
459 // Chromium only supports ASCII parameters.
460 if (!base::IsStringASCII(key_system) || !base::IsStringASCII(mime_type) ||
461 !base::IsStringASCII(codecs)) {
462 return false;
465 if (key_system.isEmpty())
466 return false;
468 const std::string mime_type_ascii = base::UTF16ToASCII(mime_type);
470 std::vector<std::string> codec_vector;
471 bool strip_suffix = !net::IsStrictMediaMimeType(mime_type_ascii);
472 net::ParseCodecString(base::UTF16ToASCII(codecs), &codec_vector,
473 strip_suffix);
475 return IsSupportedKeySystemWithMediaMimeType(
476 mime_type_ascii, codec_vector, base::UTF16ToASCII(key_system));
479 WebString
480 RendererWebKitPlatformSupportImpl::MimeRegistry::mimeTypeForExtension(
481 const WebString& file_extension) {
482 if (IsPluginProcess())
483 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension);
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(
489 new MimeRegistryMsg_GetMimeTypeFromExtension(
490 base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type));
491 return base::ASCIIToUTF16(mime_type);
494 WebString RendererWebKitPlatformSupportImpl::MimeRegistry::mimeTypeFromFile(
495 const WebString& file_path) {
496 if (IsPluginProcess())
497 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path);
499 // The sandbox restricts our access to the registry, so we need to proxy
500 // these calls over to the browser process.
501 std::string mime_type;
502 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
503 base::FilePath::FromUTF16Unsafe(file_path),
504 &mime_type));
505 return base::ASCIIToUTF16(mime_type);
508 //------------------------------------------------------------------------------
510 bool RendererWebKitPlatformSupportImpl::FileUtilities::getFileInfo(
511 const WebString& path,
512 WebFileInfo& web_file_info) {
513 base::File::Info file_info;
514 base::File::Error status = base::File::FILE_ERROR_MAX;
515 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
516 base::FilePath::FromUTF16Unsafe(path), &file_info, &status)) ||
517 status != base::File::FILE_OK) {
518 return false;
520 FileInfoToWebFileInfo(file_info, &web_file_info);
521 web_file_info.platformPath = path;
522 return true;
525 bool RendererWebKitPlatformSupportImpl::FileUtilities::
526 SendSyncMessageFromAnyThread(IPC::SyncMessage* msg) const {
527 base::TimeTicks begin = base::TimeTicks::Now();
528 const bool success = thread_safe_sender_->Send(msg);
529 base::TimeDelta delta = base::TimeTicks::Now() - begin;
530 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta);
531 return success;
534 //------------------------------------------------------------------------------
536 #if defined(OS_WIN)
538 bool RendererWebKitPlatformSupportImpl::SandboxSupport::ensureFontLoaded(
539 HFONT font) {
540 LOGFONT logfont;
541 GetObject(font, sizeof(LOGFONT), &logfont);
542 RenderThread::Get()->PreCacheFont(logfont);
543 return true;
546 #elif defined(OS_MACOSX)
548 bool RendererWebKitPlatformSupportImpl::SandboxSupport::loadFont(
549 NSFont* src_font, CGFontRef* out, uint32* font_id) {
550 uint32 font_data_size;
551 FontDescriptor src_font_descriptor(src_font);
552 base::SharedMemoryHandle font_data;
553 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
554 src_font_descriptor, &font_data_size, &font_data, font_id))) {
555 *out = NULL;
556 *font_id = 0;
557 return false;
560 if (font_data_size == 0 || font_data == base::SharedMemory::NULLHandle() ||
561 *font_id == 0) {
562 LOG(ERROR) << "Bad response from ViewHostMsg_LoadFont() for " <<
563 src_font_descriptor.font_name;
564 *out = NULL;
565 *font_id = 0;
566 return false;
569 // TODO(jeremy): Need to call back into WebKit to make sure that the font
570 // isn't already activated, based on the font id. If it's already
571 // activated, don't reactivate it here - crbug.com/72727 .
573 return FontLoader::CGFontRefFromBuffer(font_data, font_data_size, out);
576 #elif defined(OS_ANDROID)
578 // WebKit doesn't use WebSandboxSupport on android so we don't need to
579 // implement anything here. This is cleaner to support than excluding the
580 // whole class for android.
582 #elif defined(OS_POSIX)
584 void
585 RendererWebKitPlatformSupportImpl::SandboxSupport::getFallbackFontForCharacter(
586 blink::WebUChar32 character,
587 const char* preferred_locale,
588 blink::WebFallbackFont* fallbackFont) {
589 base::AutoLock lock(unicode_font_families_mutex_);
590 const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
591 unicode_font_families_.find(character);
592 if (iter != unicode_font_families_.end()) {
593 fallbackFont->name = iter->second.name;
594 fallbackFont->filename = iter->second.filename;
595 fallbackFont->fontconfigInterfaceId = iter->second.fontconfigInterfaceId;
596 fallbackFont->ttcIndex = iter->second.ttcIndex;
597 fallbackFont->isBold = iter->second.isBold;
598 fallbackFont->isItalic = iter->second.isItalic;
599 return;
602 GetFallbackFontForCharacter(character, preferred_locale, fallbackFont);
603 unicode_font_families_.insert(std::make_pair(character, *fallbackFont));
606 void
607 RendererWebKitPlatformSupportImpl::SandboxSupport::getRenderStyleForStrike(
608 const char* family, int sizeAndStyle, blink::WebFontRenderStyle* out) {
609 GetRenderStyleForStrike(family, sizeAndStyle, out);
612 #endif
614 //------------------------------------------------------------------------------
616 Platform::FileHandle
617 RendererWebKitPlatformSupportImpl::databaseOpenFile(
618 const WebString& vfs_file_name, int desired_flags) {
619 return DatabaseUtil::DatabaseOpenFile(
620 vfs_file_name, desired_flags, sync_message_filter_.get());
623 int RendererWebKitPlatformSupportImpl::databaseDeleteFile(
624 const WebString& vfs_file_name, bool sync_dir) {
625 return DatabaseUtil::DatabaseDeleteFile(
626 vfs_file_name, sync_dir, sync_message_filter_.get());
629 long RendererWebKitPlatformSupportImpl::databaseGetFileAttributes(
630 const WebString& vfs_file_name) {
631 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name,
632 sync_message_filter_.get());
635 long long RendererWebKitPlatformSupportImpl::databaseGetFileSize(
636 const WebString& vfs_file_name) {
637 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name,
638 sync_message_filter_.get());
641 long long RendererWebKitPlatformSupportImpl::databaseGetSpaceAvailableForOrigin(
642 const WebString& origin_identifier) {
643 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier,
644 sync_message_filter_.get());
647 bool RendererWebKitPlatformSupportImpl::canAccelerate2dCanvas() {
648 RenderThreadImpl* thread = RenderThreadImpl::current();
649 GpuChannelHost* host = thread->EstablishGpuChannelSync(
650 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D);
651 if (!host)
652 return false;
654 return host->gpu_info().SupportsAccelerated2dCanvas();
657 bool RendererWebKitPlatformSupportImpl::isThreadedCompositingEnabled() {
658 RenderThreadImpl* thread = RenderThreadImpl::current();
659 // thread can be NULL in tests.
660 return thread && thread->compositor_message_loop_proxy().get();
663 double RendererWebKitPlatformSupportImpl::audioHardwareSampleRate() {
664 RenderThreadImpl* thread = RenderThreadImpl::current();
665 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
668 size_t RendererWebKitPlatformSupportImpl::audioHardwareBufferSize() {
669 RenderThreadImpl* thread = RenderThreadImpl::current();
670 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
673 unsigned RendererWebKitPlatformSupportImpl::audioHardwareOutputChannels() {
674 RenderThreadImpl* thread = RenderThreadImpl::current();
675 return thread->GetAudioHardwareConfig()->GetOutputChannels();
678 WebDatabaseObserver* RendererWebKitPlatformSupportImpl::databaseObserver() {
679 return web_database_observer_impl_.get();
682 WebAudioDevice*
683 RendererWebKitPlatformSupportImpl::createAudioDevice(
684 size_t buffer_size,
685 unsigned input_channels,
686 unsigned channels,
687 double sample_rate,
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);
693 if (mock_device)
694 return mock_device;
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 // TODO(crogers): WebKit should give the channel layout instead of the hard
700 // channel count.
701 media::ChannelLayout layout = media::CHANNEL_LAYOUT_UNSUPPORTED;
702 switch (channels) {
703 case 1:
704 layout = media::CHANNEL_LAYOUT_MONO;
705 break;
706 case 2:
707 layout = media::CHANNEL_LAYOUT_STEREO;
708 break;
709 case 3:
710 layout = media::CHANNEL_LAYOUT_2_1;
711 break;
712 case 4:
713 layout = media::CHANNEL_LAYOUT_4_0;
714 break;
715 case 5:
716 layout = media::CHANNEL_LAYOUT_5_0;
717 break;
718 case 6:
719 layout = media::CHANNEL_LAYOUT_5_1;
720 break;
721 case 7:
722 layout = media::CHANNEL_LAYOUT_7_0;
723 break;
724 case 8:
725 layout = media::CHANNEL_LAYOUT_7_1;
726 break;
727 default:
728 layout = media::CHANNEL_LAYOUT_STEREO;
731 int session_id = 0;
732 if (input_device_id.isNull() ||
733 !base::StringToInt(base::UTF16ToUTF8(input_device_id), &session_id)) {
734 if (input_channels > 0)
735 DLOG(WARNING) << "createAudioDevice(): request for audio input ignored";
737 input_channels = 0;
740 media::AudioParameters params(
741 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
742 layout, input_channels,
743 static_cast<int>(sample_rate), 16, buffer_size,
744 media::AudioParameters::NO_EFFECTS);
746 return new RendererWebAudioDeviceImpl(params, callback, session_id);
749 #if defined(OS_ANDROID)
750 bool RendererWebKitPlatformSupportImpl::loadAudioResource(
751 blink::WebAudioBus* destination_bus, const char* audio_file_data,
752 size_t data_size) {
753 return DecodeAudioFileData(destination_bus,
754 audio_file_data,
755 data_size,
756 thread_safe_sender_);
758 #else
759 bool RendererWebKitPlatformSupportImpl::loadAudioResource(
760 blink::WebAudioBus* destination_bus, const char* audio_file_data,
761 size_t data_size) {
762 return DecodeAudioFileData(
763 destination_bus, audio_file_data, data_size);
765 #endif // defined(OS_ANDROID)
767 //------------------------------------------------------------------------------
769 blink::WebMIDIAccessor*
770 RendererWebKitPlatformSupportImpl::createMIDIAccessor(
771 blink::WebMIDIAccessorClient* client) {
772 blink::WebMIDIAccessor* accessor =
773 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client);
774 if (accessor)
775 return accessor;
777 return new RendererWebMIDIAccessorImpl(client);
780 void RendererWebKitPlatformSupportImpl::getPluginList(
781 bool refresh,
782 blink::WebPluginListBuilder* builder) {
783 #if defined(ENABLE_PLUGINS)
784 std::vector<WebPluginInfo> plugins;
785 if (!plugin_refresh_allowed_)
786 refresh = false;
787 RenderThread::Get()->Send(
788 new ViewHostMsg_GetPlugins(refresh, &plugins));
789 for (size_t i = 0; i < plugins.size(); ++i) {
790 const WebPluginInfo& plugin = plugins[i];
792 builder->addPlugin(
793 plugin.name, plugin.desc,
794 plugin.path.BaseName().AsUTF16Unsafe());
796 for (size_t j = 0; j < plugin.mime_types.size(); ++j) {
797 const WebPluginMimeType& mime_type = plugin.mime_types[j];
799 builder->addMediaTypeToLastPlugin(
800 WebString::fromUTF8(mime_type.mime_type), mime_type.description);
802 for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
803 builder->addFileExtensionToLastMediaType(
804 WebString::fromUTF8(mime_type.file_extensions[k]));
808 #endif
811 //------------------------------------------------------------------------------
813 blink::WebPublicSuffixList*
814 RendererWebKitPlatformSupportImpl::publicSuffixList() {
815 return &public_suffix_list_;
818 //------------------------------------------------------------------------------
820 blink::WebString
821 RendererWebKitPlatformSupportImpl::signedPublicKeyAndChallengeString(
822 unsigned key_size_index,
823 const blink::WebString& challenge,
824 const blink::WebURL& url) {
825 std::string signed_public_key;
826 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
827 static_cast<uint32>(key_size_index),
828 challenge.utf8(),
829 GURL(url),
830 &signed_public_key));
831 return WebString::fromUTF8(signed_public_key);
834 //------------------------------------------------------------------------------
836 void RendererWebKitPlatformSupportImpl::screenColorProfile(
837 WebVector<char>* to_profile) {
838 #if defined(OS_WIN)
839 // On Windows screen color profile is only available in the browser.
840 std::vector<char> profile;
841 // This Send() can be called from any impl-side thread. Use a thread
842 // safe send to avoid crashing trying to access RenderThread::Get(),
843 // which is not accessible from arbitrary threads.
844 thread_safe_sender_->Send(
845 new ViewHostMsg_GetMonitorColorProfile(&profile));
846 *to_profile = profile;
847 #else
848 // On other platforms, the primary monitor color profile can be read
849 // directly.
850 gfx::ColorProfile profile;
851 *to_profile = profile.profile();
852 #endif
855 //------------------------------------------------------------------------------
857 blink::WebScrollbarBehavior*
858 RendererWebKitPlatformSupportImpl::scrollbarBehavior() {
859 return web_scrollbar_behavior_.get();
862 //------------------------------------------------------------------------------
864 WebBlobRegistry* RendererWebKitPlatformSupportImpl::blobRegistry() {
865 // blob_registry_ can be NULL when running some tests.
866 return blob_registry_.get();
869 //------------------------------------------------------------------------------
871 void RendererWebKitPlatformSupportImpl::sampleGamepads(WebGamepads& gamepads) {
872 PlatformEventObserverBase* observer =
873 platform_event_observers_.Lookup(blink::WebPlatformEventGamepad);
874 if (!observer)
875 return;
876 static_cast<RendererGamepadProvider*>(observer)->SampleGamepads(gamepads);
879 //------------------------------------------------------------------------------
881 WebRTCPeerConnectionHandler*
882 RendererWebKitPlatformSupportImpl::createRTCPeerConnectionHandler(
883 WebRTCPeerConnectionHandlerClient* client) {
884 RenderThreadImpl* render_thread = RenderThreadImpl::current();
885 DCHECK(render_thread);
886 if (!render_thread)
887 return NULL;
889 #if defined(ENABLE_WEBRTC)
890 WebRTCPeerConnectionHandler* peer_connection_handler =
891 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
892 client);
893 if (peer_connection_handler)
894 return peer_connection_handler;
896 PeerConnectionDependencyFactory* rtc_dependency_factory =
897 render_thread->GetPeerConnectionDependencyFactory();
898 return rtc_dependency_factory->CreateRTCPeerConnectionHandler(client);
899 #else
900 return NULL;
901 #endif // defined(ENABLE_WEBRTC)
904 //------------------------------------------------------------------------------
906 WebMediaStreamCenter*
907 RendererWebKitPlatformSupportImpl::createMediaStreamCenter(
908 WebMediaStreamCenterClient* client) {
909 RenderThreadImpl* render_thread = RenderThreadImpl::current();
910 DCHECK(render_thread);
911 if (!render_thread)
912 return NULL;
913 return render_thread->CreateMediaStreamCenter(client);
916 // static
917 bool RendererWebKitPlatformSupportImpl::SetSandboxEnabledForTesting(
918 bool enable) {
919 bool was_enabled = g_sandbox_enabled;
920 g_sandbox_enabled = enable;
921 return was_enabled;
924 //------------------------------------------------------------------------------
926 blink::WebSpeechSynthesizer*
927 RendererWebKitPlatformSupportImpl::createSpeechSynthesizer(
928 blink::WebSpeechSynthesizerClient* client) {
929 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client);
932 //------------------------------------------------------------------------------
934 bool RendererWebKitPlatformSupportImpl::processMemorySizesInBytes(
935 size_t* private_bytes, size_t* shared_bytes) {
936 content::RenderThread::Get()->Send(
937 new ViewHostMsg_GetProcessMemorySizes(private_bytes, shared_bytes));
938 return true;
941 //------------------------------------------------------------------------------
943 blink::WebGraphicsContext3D*
944 RendererWebKitPlatformSupportImpl::createOffscreenGraphicsContext3D(
945 const blink::WebGraphicsContext3D::Attributes& attributes) {
946 return createOffscreenGraphicsContext3D(attributes, NULL);
949 blink::WebGraphicsContext3D*
950 RendererWebKitPlatformSupportImpl::createOffscreenGraphicsContext3D(
951 const blink::WebGraphicsContext3D::Attributes& attributes,
952 blink::WebGraphicsContext3D* share_context) {
953 if (!RenderThreadImpl::current())
954 return NULL;
956 #if defined(OS_ANDROID)
957 if (SynchronousCompositorFactory* factory =
958 SynchronousCompositorFactory::GetInstance()) {
959 return factory->CreateOffscreenGraphicsContext3D(attributes);
961 #endif
963 scoped_refptr<GpuChannelHost> gpu_channel_host(
964 RenderThreadImpl::current()->EstablishGpuChannelSync(
965 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
967 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
968 bool lose_context_when_out_of_memory = false;
969 return WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
970 gpu_channel_host.get(),
971 attributes,
972 lose_context_when_out_of_memory,
973 GURL(attributes.topDocumentURL),
974 limits,
975 static_cast<WebGraphicsContext3DCommandBufferImpl*>(share_context));
978 //------------------------------------------------------------------------------
980 blink::WebGraphicsContext3DProvider* RendererWebKitPlatformSupportImpl::
981 createSharedOffscreenGraphicsContext3DProvider() {
982 scoped_refptr<webkit::gpu::ContextProviderWebContext> provider =
983 RenderThreadImpl::current()->SharedMainThreadContextProvider();
984 if (!provider.get())
985 return NULL;
986 return new WebGraphicsContext3DProviderImpl(provider);
989 //------------------------------------------------------------------------------
991 blink::WebCompositorSupport*
992 RendererWebKitPlatformSupportImpl::compositorSupport() {
993 return &compositor_support_;
996 //------------------------------------------------------------------------------
998 blink::WebString RendererWebKitPlatformSupportImpl::convertIDNToUnicode(
999 const blink::WebString& host,
1000 const blink::WebString& languages) {
1001 return net::IDNToUnicode(host.utf8(), languages.utf8());
1004 //------------------------------------------------------------------------------
1006 // static
1007 void RendererWebKitPlatformSupportImpl::SetMockDeviceLightDataForTesting(
1008 double data) {
1009 g_test_device_light_data = data;
1012 //------------------------------------------------------------------------------
1014 // static
1015 void RendererWebKitPlatformSupportImpl::SetMockDeviceMotionDataForTesting(
1016 const blink::WebDeviceMotionData& data) {
1017 g_test_device_motion_data.Get() = data;
1020 //------------------------------------------------------------------------------
1022 // static
1023 void RendererWebKitPlatformSupportImpl::SetMockDeviceOrientationDataForTesting(
1024 const blink::WebDeviceOrientationData& data) {
1025 g_test_device_orientation_data.Get() = data;
1028 //------------------------------------------------------------------------------
1030 void RendererWebKitPlatformSupportImpl::vibrate(unsigned int milliseconds) {
1031 RenderThread::Get()->Send(
1032 new ViewHostMsg_Vibrate(base::checked_cast<int64>(milliseconds)));
1035 void RendererWebKitPlatformSupportImpl::cancelVibration() {
1036 RenderThread::Get()->Send(new ViewHostMsg_CancelVibration());
1039 //------------------------------------------------------------------------------
1041 // static
1042 PlatformEventObserverBase*
1043 RendererWebKitPlatformSupportImpl::CreatePlatformEventObserverFromType(
1044 blink::WebPlatformEventType type) {
1045 RenderThread* thread = RenderThreadImpl::current();
1047 // When running layout tests, those observers should not listen to the actual
1048 // hardware changes. In order to make that happen, they will receive a null
1049 // thread.
1050 if (thread && RenderThreadImpl::current()->layout_test_mode())
1051 thread = 0;
1053 switch (type) {
1054 case blink::WebPlatformEventDeviceMotion: {
1055 return new DeviceMotionEventPump(thread);
1057 case blink::WebPlatformEventDeviceOrientation: {
1058 return new DeviceOrientationEventPump(thread);
1060 case blink::WebPlatformEventDeviceLight: {
1061 return new DeviceLightEventPump(thread);
1063 case blink::WebPlatformEventBattery: {
1064 return new BatteryStatusDispatcher(thread);
1066 case blink::WebPlatformEventGamepad:
1067 return new GamepadSharedMemoryReader(thread);
1068 break;
1069 case blink::WebPlatformEventScreenOrientation:
1070 return new ScreenOrientationObserver();
1071 default:
1072 // A default statement is required to prevent compilation errors when Blink
1073 // adds a new type.
1074 VLOG(1) << "RendererWebKitPlatformSupportImpl::startListening() with "
1075 "unknown type.";
1078 return 0;
1081 void RendererWebKitPlatformSupportImpl::SetPlatformEventObserverForTesting(
1082 blink::WebPlatformEventType type,
1083 scoped_ptr<PlatformEventObserverBase> observer) {
1084 if (platform_event_observers_.Lookup(type))
1085 platform_event_observers_.Remove(type);
1086 platform_event_observers_.AddWithID(observer.release(), type);
1089 void RendererWebKitPlatformSupportImpl::startListening(
1090 blink::WebPlatformEventType type,
1091 blink::WebPlatformEventListener* listener) {
1092 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1093 if (!observer) {
1094 observer = CreatePlatformEventObserverFromType(type);
1095 if (!observer)
1096 return;
1097 platform_event_observers_.AddWithID(observer, static_cast<int32>(type));
1099 observer->Start(listener);
1101 // Device events (motion, orientation and light) expect to get an event fired
1102 // as soon as a listener is registered if a fake data was passed before.
1103 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1104 // using this broken pattern.
1105 if (RenderThreadImpl::current() &&
1106 RenderThreadImpl::current()->layout_test_mode() &&
1107 (type == blink::WebPlatformEventDeviceMotion ||
1108 type == blink::WebPlatformEventDeviceOrientation ||
1109 type == blink::WebPlatformEventDeviceLight)) {
1110 SendFakeDeviceEventDataForTesting(type);
1114 void RendererWebKitPlatformSupportImpl::SendFakeDeviceEventDataForTesting(
1115 blink::WebPlatformEventType type) {
1116 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1117 CHECK(observer);
1119 void* data = 0;
1121 switch (type) {
1122 case blink::WebPlatformEventDeviceMotion:
1123 if (!(g_test_device_motion_data == 0))
1124 data = &g_test_device_motion_data.Get();
1125 break;
1126 case blink::WebPlatformEventDeviceOrientation:
1127 if (!(g_test_device_orientation_data == 0))
1128 data = &g_test_device_orientation_data.Get();
1129 break;
1130 case blink::WebPlatformEventDeviceLight:
1131 if (g_test_device_light_data >= 0)
1132 data = &g_test_device_light_data;
1133 break;
1134 default:
1135 NOTREACHED();
1136 break;
1139 if (!data)
1140 return;
1142 base::MessageLoopProxy::current()->PostTask(
1143 FROM_HERE,
1144 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting,
1145 base::Unretained(observer), data));
1148 void RendererWebKitPlatformSupportImpl::stopListening(
1149 blink::WebPlatformEventType type) {
1150 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1151 if (!observer)
1152 return;
1153 observer->Stop();
1156 //------------------------------------------------------------------------------
1158 void RendererWebKitPlatformSupportImpl::queryStorageUsageAndQuota(
1159 const blink::WebURL& storage_partition,
1160 blink::WebStorageQuotaType type,
1161 blink::WebStorageQuotaCallbacks callbacks) {
1162 if (!thread_safe_sender_.get() || !quota_message_filter_.get())
1163 return;
1164 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(),
1165 quota_message_filter_.get())
1166 ->QueryStorageUsageAndQuota(
1167 storage_partition,
1168 static_cast<storage::StorageType>(type),
1169 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
1172 //------------------------------------------------------------------------------
1174 void RendererWebKitPlatformSupportImpl::MockBatteryStatusChangedForTesting(
1175 const blink::WebBatteryStatus& status) {
1176 PlatformEventObserverBase* observer =
1177 platform_event_observers_.Lookup(blink::WebPlatformEventBattery);
1178 if (!observer)
1179 return;
1180 observer->SendFakeDataForTesting((void*)&status);
1183 } // namespace content