Hook the WebThreadImplForMessageLoop up to post taks through the blink
[chromium-blink-merge.git] / content / renderer / renderer_blink_platform_impl.cc
blob40141fcd8242985b3c5324fe3be2e4d9fab49aaa
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/renderer_blink_platform_impl.h"
7 #include "base/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/lazy_instance.h"
10 #include "base/logging.h"
11 #include "base/memory/shared_memory.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/metrics/histogram.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "content/child/bluetooth/web_bluetooth_impl.h"
18 #include "content/child/database_util.h"
19 #include "content/child/file_info_util.h"
20 #include "content/child/fileapi/webfilesystem_impl.h"
21 #include "content/child/indexed_db/webidbfactory_impl.h"
22 #include "content/child/npapi/npobject_util.h"
23 #include "content/child/quota_dispatcher.h"
24 #include "content/child/quota_message_filter.h"
25 #include "content/child/simple_webmimeregistry_impl.h"
26 #include "content/child/thread_safe_sender.h"
27 #include "content/child/web_database_observer_impl.h"
28 #include "content/child/webblobregistry_impl.h"
29 #include "content/child/webfileutilities_impl.h"
30 #include "content/child/webmessageportchannel_impl.h"
31 #include "content/common/file_utilities_messages.h"
32 #include "content/common/gpu/client/context_provider_command_buffer.h"
33 #include "content/common/gpu/client/gpu_channel_host.h"
34 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
35 #include "content/common/gpu/gpu_process_launch_causes.h"
36 #include "content/common/mime_registry_messages.h"
37 #include "content/common/view_messages.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/webplugininfo.h"
40 #include "content/public/renderer/content_renderer_client.h"
41 #include "content/renderer/battery_status/battery_status_dispatcher.h"
42 #include "content/renderer/device_sensors/device_light_event_pump.h"
43 #include "content/renderer/device_sensors/device_motion_event_pump.h"
44 #include "content/renderer/device_sensors/device_orientation_event_pump.h"
45 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
46 #include "content/renderer/gamepad_shared_memory_reader.h"
47 #include "content/renderer/media/audio_decoder.h"
48 #include "content/renderer/media/crypto/key_systems.h"
49 #include "content/renderer/media/renderer_webaudiodevice_impl.h"
50 #include "content/renderer/media/renderer_webmidiaccessor_impl.h"
51 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
52 #include "content/renderer/render_thread_impl.h"
53 #include "content/renderer/renderer_clipboard_client.h"
54 #include "content/renderer/scheduler/renderer_scheduler.h"
55 #include "content/renderer/scheduler/web_scheduler_impl.h"
56 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
57 #include "content/renderer/webclipboard_impl.h"
58 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
59 #include "content/renderer/webpublicsuffixlist_impl.h"
60 #include "gpu/config/gpu_info.h"
61 #include "ipc/ipc_sync_message_filter.h"
62 #include "media/audio/audio_output_device.h"
63 #include "media/base/audio_hardware_config.h"
64 #include "media/filters/stream_parser_factory.h"
65 #include "net/base/mime_util.h"
66 #include "net/base/net_util.h"
67 #include "storage/common/quota/quota_types.h"
68 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
69 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
70 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
71 #include "third_party/WebKit/public/platform/WebDeviceMotionListener.h"
72 #include "third_party/WebKit/public/platform/WebDeviceOrientationListener.h"
73 #include "third_party/WebKit/public/platform/WebFileInfo.h"
74 #include "third_party/WebKit/public/platform/WebGamepads.h"
75 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
76 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
77 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
78 #include "third_party/WebKit/public/platform/WebURL.h"
79 #include "third_party/WebKit/public/platform/WebVector.h"
80 #include "ui/gfx/color_profile.h"
81 #include "url/gurl.h"
82 #include "webkit/common/gpu/context_provider_web_context.h"
84 #if defined(OS_ANDROID)
85 #include "content/renderer/android/synchronous_compositor_factory.h"
86 #include "content/renderer/media/android/audio_decoder_android.h"
87 #include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
88 #endif
90 #if defined(OS_MACOSX)
91 #include "content/common/mac/font_descriptor.h"
92 #include "content/common/mac/font_loader.h"
93 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
94 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
95 #endif
97 #if defined(OS_POSIX)
98 #include "base/file_descriptor_posix.h"
99 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
100 #include <map>
101 #include <string>
103 #include "base/synchronization/lock.h"
104 #include "content/common/child_process_sandbox_support_impl_linux.h"
105 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
106 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
107 #include "third_party/icu/source/common/unicode/utf16.h"
108 #endif
109 #endif
111 #if defined(OS_WIN)
112 #include "content/common/child_process_messages.h"
113 #include "third_party/WebKit/public/platform/win/WebSandboxSupport.h"
114 #endif
116 #if defined(USE_AURA)
117 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
118 #elif !defined(OS_MACOSX)
119 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
120 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
121 #endif
123 #if defined(ENABLE_WEBRTC)
124 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
125 #endif
127 using blink::Platform;
128 using blink::WebAudioDevice;
129 using blink::WebBlobRegistry;
130 using blink::WebDatabaseObserver;
131 using blink::WebFileInfo;
132 using blink::WebFileSystem;
133 using blink::WebGamepad;
134 using blink::WebGamepads;
135 using blink::WebIDBFactory;
136 using blink::WebMIDIAccessor;
137 using blink::WebMediaStreamCenter;
138 using blink::WebMediaStreamCenterClient;
139 using blink::WebMimeRegistry;
140 using blink::WebRTCPeerConnectionHandler;
141 using blink::WebRTCPeerConnectionHandlerClient;
142 using blink::WebStorageNamespace;
143 using blink::WebString;
144 using blink::WebURL;
145 using blink::WebVector;
147 namespace content {
149 namespace {
151 bool g_sandbox_enabled = true;
152 double g_test_device_light_data = -1;
153 base::LazyInstance<blink::WebDeviceMotionData>::Leaky
154 g_test_device_motion_data = LAZY_INSTANCE_INITIALIZER;
155 base::LazyInstance<blink::WebDeviceOrientationData>::Leaky
156 g_test_device_orientation_data = LAZY_INSTANCE_INITIALIZER;
157 // Set in startListening() when running layout tests, unset in stopListening(),
158 // not owned by us.
159 blink::WebBatteryStatusListener* g_test_battery_status_listener = nullptr;
161 } // namespace
163 //------------------------------------------------------------------------------
165 class RendererBlinkPlatformImpl::MimeRegistry
166 : public SimpleWebMimeRegistryImpl {
167 public:
168 virtual blink::WebMimeRegistry::SupportsType supportsMediaMIMEType(
169 const blink::WebString& mime_type,
170 const blink::WebString& codecs,
171 const blink::WebString& key_system);
172 virtual bool supportsMediaSourceMIMEType(const blink::WebString& mime_type,
173 const blink::WebString& codecs);
174 virtual bool supportsEncryptedMediaMIMEType(const WebString& key_system,
175 const WebString& mime_type,
176 const WebString& codecs) override;
177 virtual blink::WebString mimeTypeForExtension(
178 const blink::WebString& file_extension);
179 virtual blink::WebString mimeTypeFromFile(
180 const blink::WebString& file_path);
183 class RendererBlinkPlatformImpl::FileUtilities : public WebFileUtilitiesImpl {
184 public:
185 explicit FileUtilities(ThreadSafeSender* sender)
186 : thread_safe_sender_(sender) {}
187 virtual bool getFileInfo(const WebString& path, WebFileInfo& result);
188 private:
189 bool SendSyncMessageFromAnyThread(IPC::SyncMessage* msg) const;
190 scoped_refptr<ThreadSafeSender> thread_safe_sender_;
193 #if defined(OS_ANDROID)
194 // WebKit doesn't use WebSandboxSupport on android so we don't need to
195 // implement anything here.
196 class RendererBlinkPlatformImpl::SandboxSupport {};
197 #else
198 class RendererBlinkPlatformImpl::SandboxSupport
199 : public blink::WebSandboxSupport {
200 public:
201 virtual ~SandboxSupport() {}
203 #if defined(OS_WIN)
204 virtual bool ensureFontLoaded(HFONT);
205 #elif defined(OS_MACOSX)
206 virtual bool loadFont(
207 NSFont* src_font,
208 CGFontRef* container,
209 uint32* font_id);
210 #elif defined(OS_POSIX)
211 virtual void getFallbackFontForCharacter(
212 blink::WebUChar32 character,
213 const char* preferred_locale,
214 blink::WebFallbackFont* fallbackFont);
215 virtual void getRenderStyleForStrike(
216 const char* family, int sizeAndStyle, blink::WebFontRenderStyle* out);
218 private:
219 // WebKit likes to ask us for the correct font family to use for a set of
220 // unicode code points. It needs this information frequently so we cache it
221 // here.
222 base::Lock unicode_font_families_mutex_;
223 std::map<int32_t, blink::WebFallbackFont> unicode_font_families_;
224 #endif
226 #endif // defined(OS_ANDROID)
228 //------------------------------------------------------------------------------
230 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
231 RendererScheduler* renderer_scheduler)
232 : BlinkPlatformImpl(renderer_scheduler->DefaultTaskRunner()),
233 web_scheduler_(new WebSchedulerImpl(renderer_scheduler)),
234 clipboard_client_(new RendererClipboardClient),
235 clipboard_(new WebClipboardImpl(clipboard_client_.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 child_thread_loop_(base::MessageLoopProxy::current()),
241 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl),
242 bluetooth_(new WebBluetoothImpl) {
243 if (g_sandbox_enabled && sandboxEnabled()) {
244 sandbox_support_.reset(new RendererBlinkPlatformImpl::SandboxSupport);
245 } else {
246 DVLOG(1) << "Disabling sandbox support for testing.";
249 // ChildThread may not exist in some tests.
250 if (ChildThread::current()) {
251 sync_message_filter_ = ChildThread::current()->sync_message_filter();
252 thread_safe_sender_ = ChildThread::current()->thread_safe_sender();
253 quota_message_filter_ = ChildThread::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::WebScheduler* RendererBlinkPlatformImpl::scheduler() {
268 return web_scheduler_.get();
271 blink::WebClipboard* RendererBlinkPlatformImpl::clipboard() {
272 blink::WebClipboard* clipboard =
273 GetContentClient()->renderer()->OverrideWebClipboard();
274 if (clipboard)
275 return clipboard;
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)
293 // WebKit doesn't use WebSandboxSupport on android.
294 return NULL;
295 #else
296 return sandbox_support_.get();
297 #endif
300 blink::WebCookieJar* RendererBlinkPlatformImpl::cookieJar() {
301 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
302 return NULL;
305 blink::WebThemeEngine* RendererBlinkPlatformImpl::themeEngine() {
306 blink::WebThemeEngine* theme_engine =
307 GetContentClient()->renderer()->OverrideThemeEngine();
308 if (theme_engine)
309 return theme_engine;
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 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);
324 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
325 const char* canonical_url,
326 size_t length) {
327 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url, length);
330 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash) {
331 return GetContentClient()->renderer()->IsLinkVisited(link_hash);
334 void RendererBlinkPlatformImpl::createMessageChannel(
335 blink::WebMessagePortChannel** channel1,
336 blink::WebMessagePortChannel** channel2) {
337 WebMessagePortChannelImpl::CreatePair(
338 child_thread_loop_.get(), channel1, channel2);
341 blink::WebPrescientNetworking*
342 RendererBlinkPlatformImpl::prescientNetworking() {
343 return GetContentClient()->renderer()->GetPrescientNetworking();
346 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL& url,
347 double response_time,
348 const char* data,
349 size_t size) {
350 // Let the browser know we generated cacheable metadata for this resource. The
351 // browser may cache it and return it on subsequent responses to speed
352 // the processing of this resource.
353 std::vector<char> copy(data, data + size);
354 RenderThread::Get()->Send(
355 new ViewHostMsg_DidGenerateCacheableMetadata(url, response_time, copy));
358 WebString RendererBlinkPlatformImpl::defaultLocale() {
359 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
362 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled) {
363 if (enabled) {
364 // We should not get more enables than disables, but we want it to be a
365 // non-fatal error if it does happen.
366 DCHECK_GT(sudden_termination_disables_, 0);
367 sudden_termination_disables_ = std::max(sudden_termination_disables_ - 1,
369 if (sudden_termination_disables_ != 0)
370 return;
371 } else {
372 sudden_termination_disables_++;
373 if (sudden_termination_disables_ != 1)
374 return;
377 RenderThread* thread = RenderThread::Get();
378 if (thread) // NULL in unittests.
379 thread->Send(new ViewHostMsg_SuddenTerminationChanged(enabled));
382 WebStorageNamespace* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
383 return new WebStorageNamespaceImpl();
387 //------------------------------------------------------------------------------
389 WebIDBFactory* RendererBlinkPlatformImpl::idbFactory() {
390 return web_idb_factory_.get();
393 //------------------------------------------------------------------------------
395 WebFileSystem* RendererBlinkPlatformImpl::fileSystem() {
396 return WebFileSystemImpl::ThreadSpecificInstance(child_thread_loop_.get());
399 //------------------------------------------------------------------------------
401 WebMimeRegistry::SupportsType
402 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
403 const WebString& mime_type,
404 const WebString& codecs,
405 const WebString& key_system) {
406 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
407 // Not supporting the container is a flat-out no.
408 if (!net::IsSupportedMediaMimeType(mime_type_ascii))
409 return IsNotSupported;
411 if (!key_system.isEmpty()) {
412 // Check whether the key system is supported with the mime_type and codecs.
414 // Chromium only supports ASCII parameters.
415 if (!base::IsStringASCII(key_system))
416 return IsNotSupported;
418 std::string key_system_ascii =
419 GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system));
420 std::vector<std::string> strict_codecs;
421 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, true);
423 if (!IsSupportedKeySystemWithMediaMimeType(
424 mime_type_ascii, strict_codecs, key_system_ascii)) {
425 return IsNotSupported;
428 // Continue processing the mime_type and codecs.
431 // Check list of strict codecs to see if it is supported.
432 if (net::IsStrictMediaMimeType(mime_type_ascii)) {
433 // Check if the codecs are a perfect match.
434 std::vector<std::string> strict_codecs;
435 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
436 return static_cast<WebMimeRegistry::SupportsType> (
437 net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
440 // If we don't recognize the codec, it's possible we support it.
441 std::vector<std::string> parsed_codecs;
442 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
443 if (!net::AreSupportedMediaCodecs(parsed_codecs))
444 return MayBeSupported;
446 // Otherwise we have a perfect match.
447 return IsSupported;
450 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
451 const blink::WebString& mime_type,
452 const WebString& codecs) {
453 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
454 std::vector<std::string> parsed_codec_ids;
455 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
456 if (mime_type_ascii.empty())
457 return false;
458 return media::StreamParserFactory::IsTypeSupported(
459 mime_type_ascii, parsed_codec_ids);
462 bool RendererBlinkPlatformImpl::MimeRegistry::supportsEncryptedMediaMIMEType(
463 const WebString& key_system,
464 const WebString& mime_type,
465 const WebString& codecs) {
466 // Chromium only supports ASCII parameters.
467 if (!base::IsStringASCII(key_system) || !base::IsStringASCII(mime_type) ||
468 !base::IsStringASCII(codecs)) {
469 return false;
472 if (key_system.isEmpty())
473 return false;
475 const std::string mime_type_ascii = base::UTF16ToASCII(mime_type);
477 std::vector<std::string> codec_vector;
478 bool strip_suffix = !net::IsStrictMediaMimeType(mime_type_ascii);
479 net::ParseCodecString(base::UTF16ToASCII(codecs), &codec_vector,
480 strip_suffix);
482 return IsSupportedKeySystemWithMediaMimeType(
483 mime_type_ascii, codec_vector, base::UTF16ToASCII(key_system));
486 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
487 const WebString& file_extension) {
488 if (IsPluginProcess())
489 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension);
491 // The sandbox restricts our access to the registry, so we need to proxy
492 // these calls over to the browser process.
493 std::string mime_type;
494 RenderThread::Get()->Send(
495 new MimeRegistryMsg_GetMimeTypeFromExtension(
496 base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type));
497 return base::ASCIIToUTF16(mime_type);
500 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
501 const WebString& file_path) {
502 if (IsPluginProcess())
503 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path);
505 // The sandbox restricts our access to the registry, so we need to proxy
506 // these calls over to the browser process.
507 std::string mime_type;
508 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
509 base::FilePath::FromUTF16Unsafe(file_path),
510 &mime_type));
511 return base::ASCIIToUTF16(mime_type);
514 //------------------------------------------------------------------------------
516 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
517 const WebString& path,
518 WebFileInfo& web_file_info) {
519 base::File::Info file_info;
520 base::File::Error status = base::File::FILE_ERROR_MAX;
521 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
522 base::FilePath::FromUTF16Unsafe(path), &file_info, &status)) ||
523 status != base::File::FILE_OK) {
524 return false;
526 FileInfoToWebFileInfo(file_info, &web_file_info);
527 web_file_info.platformPath = path;
528 return true;
531 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
532 IPC::SyncMessage* msg) const {
533 base::TimeTicks begin = base::TimeTicks::Now();
534 const bool success = thread_safe_sender_->Send(msg);
535 base::TimeDelta delta = base::TimeTicks::Now() - begin;
536 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta);
537 return success;
540 //------------------------------------------------------------------------------
542 #if defined(OS_WIN)
544 bool RendererBlinkPlatformImpl::SandboxSupport::ensureFontLoaded(HFONT font) {
545 LOGFONT logfont;
546 GetObject(font, sizeof(LOGFONT), &logfont);
547 RenderThread::Get()->PreCacheFont(logfont);
548 return true;
551 #elif defined(OS_MACOSX)
553 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont* src_font,
554 CGFontRef* out,
555 uint32* font_id) {
556 uint32 font_data_size;
557 FontDescriptor src_font_descriptor(src_font);
558 base::SharedMemoryHandle font_data;
559 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
560 src_font_descriptor, &font_data_size, &font_data, font_id))) {
561 *out = NULL;
562 *font_id = 0;
563 return false;
566 if (font_data_size == 0 || font_data == base::SharedMemory::NULLHandle() ||
567 *font_id == 0) {
568 LOG(ERROR) << "Bad response from ViewHostMsg_LoadFont() for " <<
569 src_font_descriptor.font_name;
570 *out = NULL;
571 *font_id = 0;
572 return false;
575 // TODO(jeremy): Need to call back into WebKit to make sure that the font
576 // isn't already activated, based on the font id. If it's already
577 // activated, don't reactivate it here - crbug.com/72727 .
579 return FontLoader::CGFontRefFromBuffer(font_data, font_data_size, out);
582 #elif defined(OS_ANDROID)
584 // WebKit doesn't use WebSandboxSupport on android so we don't need to
585 // implement anything here. This is cleaner to support than excluding the
586 // whole class for android.
588 #elif defined(OS_POSIX)
590 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
591 blink::WebUChar32 character,
592 const char* preferred_locale,
593 blink::WebFallbackFont* fallbackFont) {
594 base::AutoLock lock(unicode_font_families_mutex_);
595 const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
596 unicode_font_families_.find(character);
597 if (iter != unicode_font_families_.end()) {
598 fallbackFont->name = iter->second.name;
599 fallbackFont->filename = iter->second.filename;
600 fallbackFont->fontconfigInterfaceId = iter->second.fontconfigInterfaceId;
601 fallbackFont->ttcIndex = iter->second.ttcIndex;
602 fallbackFont->isBold = iter->second.isBold;
603 fallbackFont->isItalic = iter->second.isItalic;
604 return;
607 GetFallbackFontForCharacter(character, preferred_locale, fallbackFont);
608 unicode_font_families_.insert(std::make_pair(character, *fallbackFont));
611 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
612 const char* family,
613 int sizeAndStyle,
614 blink::WebFontRenderStyle* out) {
615 GetRenderStyleForStrike(family, sizeAndStyle, out);
618 #endif
620 //------------------------------------------------------------------------------
622 Platform::FileHandle RendererBlinkPlatformImpl::databaseOpenFile(
623 const WebString& vfs_file_name,
624 int desired_flags) {
625 return DatabaseUtil::DatabaseOpenFile(
626 vfs_file_name, desired_flags, sync_message_filter_.get());
629 int RendererBlinkPlatformImpl::databaseDeleteFile(
630 const WebString& vfs_file_name,
631 bool sync_dir) {
632 return DatabaseUtil::DatabaseDeleteFile(
633 vfs_file_name, sync_dir, sync_message_filter_.get());
636 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
637 const WebString& vfs_file_name) {
638 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name,
639 sync_message_filter_.get());
642 long long RendererBlinkPlatformImpl::databaseGetFileSize(
643 const WebString& vfs_file_name) {
644 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name,
645 sync_message_filter_.get());
648 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
649 const WebString& origin_identifier) {
650 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier,
651 sync_message_filter_.get());
654 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
655 RenderThreadImpl* thread = RenderThreadImpl::current();
656 GpuChannelHost* host = thread->EstablishGpuChannelSync(
657 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D);
658 if (!host)
659 return false;
661 return host->gpu_info().SupportsAccelerated2dCanvas();
664 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
665 RenderThreadImpl* thread = RenderThreadImpl::current();
666 // thread can be NULL in tests.
667 return thread && thread->compositor_message_loop_proxy().get();
670 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
671 RenderThreadImpl* thread = RenderThreadImpl::current();
672 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
675 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
676 RenderThreadImpl* thread = RenderThreadImpl::current();
677 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
680 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
681 RenderThreadImpl* thread = RenderThreadImpl::current();
682 return thread->GetAudioHardwareConfig()->GetOutputChannels();
685 WebDatabaseObserver* RendererBlinkPlatformImpl::databaseObserver() {
686 return web_database_observer_impl_.get();
689 WebAudioDevice* RendererBlinkPlatformImpl::createAudioDevice(
690 size_t buffer_size,
691 unsigned input_channels,
692 unsigned channels,
693 double sample_rate,
694 WebAudioDevice::RenderCallback* callback,
695 const blink::WebString& input_device_id) {
696 // Use a mock for testing.
697 blink::WebAudioDevice* mock_device =
698 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate);
699 if (mock_device)
700 return mock_device;
702 // The |channels| does not exactly identify the channel layout of the
703 // device. The switch statement below assigns a best guess to the channel
704 // layout based on number of channels.
705 // TODO(crogers): WebKit should give the channel layout instead of the hard
706 // channel count.
707 media::ChannelLayout layout = media::CHANNEL_LAYOUT_UNSUPPORTED;
708 switch (channels) {
709 case 1:
710 layout = media::CHANNEL_LAYOUT_MONO;
711 break;
712 case 2:
713 layout = media::CHANNEL_LAYOUT_STEREO;
714 break;
715 case 3:
716 layout = media::CHANNEL_LAYOUT_2_1;
717 break;
718 case 4:
719 layout = media::CHANNEL_LAYOUT_4_0;
720 break;
721 case 5:
722 layout = media::CHANNEL_LAYOUT_5_0;
723 break;
724 case 6:
725 layout = media::CHANNEL_LAYOUT_5_1;
726 break;
727 case 7:
728 layout = media::CHANNEL_LAYOUT_7_0;
729 break;
730 case 8:
731 layout = media::CHANNEL_LAYOUT_7_1;
732 break;
733 default:
734 layout = media::CHANNEL_LAYOUT_STEREO;
737 int session_id = 0;
738 if (input_device_id.isNull() ||
739 !base::StringToInt(base::UTF16ToUTF8(input_device_id), &session_id)) {
740 if (input_channels > 0)
741 DLOG(WARNING) << "createAudioDevice(): request for audio input ignored";
743 input_channels = 0;
746 media::AudioParameters params(
747 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
748 layout, static_cast<int>(sample_rate), 16, buffer_size,
749 media::AudioParameters::NO_EFFECTS);
751 return new RendererWebAudioDeviceImpl(params, callback, session_id);
754 #if defined(OS_ANDROID)
755 bool RendererBlinkPlatformImpl::loadAudioResource(
756 blink::WebAudioBus* destination_bus,
757 const char* audio_file_data,
758 size_t data_size) {
759 return DecodeAudioFileData(destination_bus,
760 audio_file_data,
761 data_size,
762 thread_safe_sender_);
764 #else
765 bool RendererBlinkPlatformImpl::loadAudioResource(
766 blink::WebAudioBus* destination_bus,
767 const char* audio_file_data,
768 size_t data_size) {
769 return DecodeAudioFileData(
770 destination_bus, audio_file_data, data_size);
772 #endif // defined(OS_ANDROID)
774 //------------------------------------------------------------------------------
776 blink::WebMIDIAccessor* RendererBlinkPlatformImpl::createMIDIAccessor(
777 blink::WebMIDIAccessorClient* client) {
778 blink::WebMIDIAccessor* accessor =
779 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client);
780 if (accessor)
781 return accessor;
783 return new RendererWebMIDIAccessorImpl(client);
786 void RendererBlinkPlatformImpl::getPluginList(
787 bool refresh,
788 blink::WebPluginListBuilder* builder) {
789 #if defined(ENABLE_PLUGINS)
790 std::vector<WebPluginInfo> plugins;
791 if (!plugin_refresh_allowed_)
792 refresh = false;
793 RenderThread::Get()->Send(
794 new ViewHostMsg_GetPlugins(refresh, &plugins));
795 for (size_t i = 0; i < plugins.size(); ++i) {
796 const WebPluginInfo& plugin = plugins[i];
798 builder->addPlugin(
799 plugin.name, plugin.desc,
800 plugin.path.BaseName().AsUTF16Unsafe());
802 for (size_t j = 0; j < plugin.mime_types.size(); ++j) {
803 const WebPluginMimeType& mime_type = plugin.mime_types[j];
805 builder->addMediaTypeToLastPlugin(
806 WebString::fromUTF8(mime_type.mime_type), mime_type.description);
808 for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
809 builder->addFileExtensionToLastMediaType(
810 WebString::fromUTF8(mime_type.file_extensions[k]));
814 #endif
817 //------------------------------------------------------------------------------
819 blink::WebPublicSuffixList* RendererBlinkPlatformImpl::publicSuffixList() {
820 return &public_suffix_list_;
823 //------------------------------------------------------------------------------
825 blink::WebString RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
826 unsigned key_size_index,
827 const blink::WebString& challenge,
828 const blink::WebURL& url) {
829 std::string signed_public_key;
830 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
831 static_cast<uint32>(key_size_index),
832 challenge.utf8(),
833 GURL(url),
834 &signed_public_key));
835 return WebString::fromUTF8(signed_public_key);
838 //------------------------------------------------------------------------------
840 void RendererBlinkPlatformImpl::screenColorProfile(
841 WebVector<char>* to_profile) {
842 #if defined(OS_WIN)
843 // On Windows screen color profile is only available in the browser.
844 std::vector<char> profile;
845 // This Send() can be called from any impl-side thread. Use a thread
846 // safe send to avoid crashing trying to access RenderThread::Get(),
847 // which is not accessible from arbitrary threads.
848 thread_safe_sender_->Send(
849 new ViewHostMsg_GetMonitorColorProfile(&profile));
850 *to_profile = profile;
851 #else
852 // On other platforms, the primary monitor color profile can be read
853 // directly.
854 gfx::ColorProfile profile;
855 *to_profile = profile.profile();
856 #endif
859 //------------------------------------------------------------------------------
861 blink::WebScrollbarBehavior* RendererBlinkPlatformImpl::scrollbarBehavior() {
862 return web_scrollbar_behavior_.get();
865 //------------------------------------------------------------------------------
867 WebBlobRegistry* RendererBlinkPlatformImpl::blobRegistry() {
868 // blob_registry_ can be NULL when running some tests.
869 return blob_registry_.get();
872 //------------------------------------------------------------------------------
874 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads& gamepads) {
875 PlatformEventObserverBase* observer =
876 platform_event_observers_.Lookup(blink::WebPlatformEventGamepad);
877 if (!observer)
878 return;
879 static_cast<RendererGamepadProvider*>(observer)->SampleGamepads(gamepads);
882 //------------------------------------------------------------------------------
884 WebRTCPeerConnectionHandler*
885 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
886 WebRTCPeerConnectionHandlerClient* client) {
887 RenderThreadImpl* render_thread = RenderThreadImpl::current();
888 DCHECK(render_thread);
889 if (!render_thread)
890 return NULL;
892 #if defined(ENABLE_WEBRTC)
893 WebRTCPeerConnectionHandler* peer_connection_handler =
894 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
895 client);
896 if (peer_connection_handler)
897 return peer_connection_handler;
899 PeerConnectionDependencyFactory* rtc_dependency_factory =
900 render_thread->GetPeerConnectionDependencyFactory();
901 return rtc_dependency_factory->CreateRTCPeerConnectionHandler(client);
902 #else
903 return NULL;
904 #endif // defined(ENABLE_WEBRTC)
907 //------------------------------------------------------------------------------
909 WebMediaStreamCenter* RendererBlinkPlatformImpl::createMediaStreamCenter(
910 WebMediaStreamCenterClient* client) {
911 RenderThreadImpl* render_thread = RenderThreadImpl::current();
912 DCHECK(render_thread);
913 if (!render_thread)
914 return NULL;
915 return render_thread->CreateMediaStreamCenter(client);
918 // static
919 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable) {
920 bool was_enabled = g_sandbox_enabled;
921 g_sandbox_enabled = enable;
922 return was_enabled;
925 //------------------------------------------------------------------------------
927 blink::WebSpeechSynthesizer* RendererBlinkPlatformImpl::createSpeechSynthesizer(
928 blink::WebSpeechSynthesizerClient* client) {
929 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client);
932 //------------------------------------------------------------------------------
934 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
935 size_t* private_bytes,
936 size_t* shared_bytes) {
937 content::RenderThread::Get()->Send(
938 new ViewHostMsg_GetProcessMemorySizes(private_bytes, shared_bytes));
939 return true;
942 //------------------------------------------------------------------------------
944 blink::WebGraphicsContext3D*
945 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
946 const blink::WebGraphicsContext3D::Attributes& attributes) {
947 return createOffscreenGraphicsContext3D(attributes, NULL);
950 blink::WebGraphicsContext3D*
951 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
952 const blink::WebGraphicsContext3D::Attributes& attributes,
953 blink::WebGraphicsContext3D* share_context) {
954 return createOffscreenGraphicsContext3D(attributes, share_context, NULL);
957 blink::WebGraphicsContext3D*
958 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
959 const blink::WebGraphicsContext3D::Attributes& attributes,
960 blink::WebGraphicsContext3D* share_context,
961 blink::WebGLInfo* gl_info) {
962 if (!RenderThreadImpl::current())
963 return NULL;
965 #if defined(OS_ANDROID)
966 if (SynchronousCompositorFactory* factory =
967 SynchronousCompositorFactory::GetInstance()) {
968 scoped_ptr<webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl>
969 in_process_context(
970 factory->CreateOffscreenGraphicsContext3D(attributes));
971 if (!in_process_context ||
972 !in_process_context->InitializeOnCurrentThread())
973 return NULL;
974 return in_process_context.release();
976 #endif
978 scoped_refptr<GpuChannelHost> gpu_channel_host(
979 RenderThreadImpl::current()->EstablishGpuChannelSync(
980 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
982 if (gpu_channel_host.get() && gl_info) {
983 const gpu::GPUInfo& gpu_info = gpu_channel_host->gpu_info();
984 gl_info->vendorInfo.assign(blink::WebString::fromUTF8(gpu_info.gl_vendor));
985 gl_info->rendererInfo.assign(
986 blink::WebString::fromUTF8(gpu_info.gl_renderer));
987 gl_info->driverVersion.assign(
988 blink::WebString::fromUTF8(gpu_info.gl_version));
991 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
992 bool lose_context_when_out_of_memory = false;
993 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
994 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
995 gpu_channel_host.get(),
996 attributes,
997 lose_context_when_out_of_memory,
998 GURL(attributes.topDocumentURL),
999 limits,
1000 static_cast<WebGraphicsContext3DCommandBufferImpl*>(share_context)));
1002 // Most likely the GPU process exited and the attempt to reconnect to it
1003 // failed. Need to try to restore the context again later.
1004 if (!context || !context->InitializeOnCurrentThread())
1005 return NULL;
1006 return context.release();
1009 //------------------------------------------------------------------------------
1011 blink::WebGraphicsContext3DProvider*
1012 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
1013 scoped_refptr<webkit::gpu::ContextProviderWebContext> provider =
1014 RenderThreadImpl::current()->SharedMainThreadContextProvider();
1015 if (!provider.get())
1016 return NULL;
1017 return new WebGraphicsContext3DProviderImpl(provider);
1020 //------------------------------------------------------------------------------
1022 blink::WebCompositorSupport* RendererBlinkPlatformImpl::compositorSupport() {
1023 return &compositor_support_;
1026 //------------------------------------------------------------------------------
1028 blink::WebString RendererBlinkPlatformImpl::convertIDNToUnicode(
1029 const blink::WebString& host,
1030 const blink::WebString& languages) {
1031 return net::IDNToUnicode(host.utf8(), languages.utf8());
1034 //------------------------------------------------------------------------------
1036 // static
1037 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data) {
1038 g_test_device_light_data = data;
1041 //------------------------------------------------------------------------------
1043 // static
1044 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1045 const blink::WebDeviceMotionData& data) {
1046 g_test_device_motion_data.Get() = data;
1049 //------------------------------------------------------------------------------
1051 // static
1052 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1053 const blink::WebDeviceOrientationData& data) {
1054 g_test_device_orientation_data.Get() = data;
1057 //------------------------------------------------------------------------------
1059 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds) {
1060 RenderThread::Get()->Send(
1061 new ViewHostMsg_Vibrate(base::checked_cast<int64>(milliseconds)));
1064 void RendererBlinkPlatformImpl::cancelVibration() {
1065 RenderThread::Get()->Send(new ViewHostMsg_CancelVibration());
1068 //------------------------------------------------------------------------------
1070 // static
1071 PlatformEventObserverBase*
1072 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1073 blink::WebPlatformEventType type) {
1074 RenderThread* thread = RenderThreadImpl::current();
1076 // When running layout tests, those observers should not listen to the actual
1077 // hardware changes. In order to make that happen, they will receive a null
1078 // thread.
1079 if (thread && RenderThreadImpl::current()->layout_test_mode())
1080 thread = NULL;
1082 switch (type) {
1083 case blink::WebPlatformEventDeviceMotion:
1084 return new DeviceMotionEventPump(thread);
1085 case blink::WebPlatformEventDeviceOrientation:
1086 return new DeviceOrientationEventPump(thread);
1087 case blink::WebPlatformEventDeviceLight:
1088 return new DeviceLightEventPump(thread);
1089 case blink::WebPlatformEventGamepad:
1090 return new GamepadSharedMemoryReader(thread);
1091 case blink::WebPlatformEventScreenOrientation:
1092 return new ScreenOrientationObserver();
1093 default:
1094 // A default statement is required to prevent compilation errors when
1095 // Blink adds a new type.
1096 VLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1097 "unknown type.";
1100 return NULL;
1103 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1104 blink::WebPlatformEventType type,
1105 scoped_ptr<PlatformEventObserverBase> observer) {
1106 DCHECK(type != blink::WebPlatformEventBattery);
1108 if (platform_event_observers_.Lookup(type))
1109 platform_event_observers_.Remove(type);
1110 platform_event_observers_.AddWithID(observer.release(), type);
1113 void RendererBlinkPlatformImpl::startListening(
1114 blink::WebPlatformEventType type,
1115 blink::WebPlatformEventListener* listener) {
1116 if (type == blink::WebPlatformEventBattery) {
1117 if (RenderThreadImpl::current() &&
1118 RenderThreadImpl::current()->layout_test_mode()) {
1119 g_test_battery_status_listener =
1120 static_cast<blink::WebBatteryStatusListener*>(listener);
1121 } else {
1122 battery_status_dispatcher_.reset(new BatteryStatusDispatcher(
1123 static_cast<blink::WebBatteryStatusListener*>(listener)));
1125 return;
1128 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1129 if (!observer) {
1130 observer = CreatePlatformEventObserverFromType(type);
1131 if (!observer)
1132 return;
1133 platform_event_observers_.AddWithID(observer, static_cast<int32>(type));
1135 observer->Start(listener);
1137 // Device events (motion, orientation and light) expect to get an event fired
1138 // as soon as a listener is registered if a fake data was passed before.
1139 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1140 // using this broken pattern.
1141 if (RenderThreadImpl::current() &&
1142 RenderThreadImpl::current()->layout_test_mode() &&
1143 (type == blink::WebPlatformEventDeviceMotion ||
1144 type == blink::WebPlatformEventDeviceOrientation ||
1145 type == blink::WebPlatformEventDeviceLight)) {
1146 SendFakeDeviceEventDataForTesting(type);
1150 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1151 blink::WebPlatformEventType type) {
1152 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1153 CHECK(observer);
1155 void* data = 0;
1157 switch (type) {
1158 case blink::WebPlatformEventDeviceMotion:
1159 if (!(g_test_device_motion_data == 0))
1160 data = &g_test_device_motion_data.Get();
1161 break;
1162 case blink::WebPlatformEventDeviceOrientation:
1163 if (!(g_test_device_orientation_data == 0))
1164 data = &g_test_device_orientation_data.Get();
1165 break;
1166 case blink::WebPlatformEventDeviceLight:
1167 if (g_test_device_light_data >= 0)
1168 data = &g_test_device_light_data;
1169 break;
1170 default:
1171 NOTREACHED();
1172 break;
1175 if (!data)
1176 return;
1178 base::MessageLoopProxy::current()->PostTask(
1179 FROM_HERE,
1180 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting,
1181 base::Unretained(observer), data));
1184 void RendererBlinkPlatformImpl::stopListening(
1185 blink::WebPlatformEventType type) {
1186 if (type == blink::WebPlatformEventBattery) {
1187 g_test_battery_status_listener = nullptr;
1188 battery_status_dispatcher_.reset();
1189 return;
1192 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1193 if (!observer)
1194 return;
1195 observer->Stop();
1198 //------------------------------------------------------------------------------
1200 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1201 const blink::WebURL& storage_partition,
1202 blink::WebStorageQuotaType type,
1203 blink::WebStorageQuotaCallbacks callbacks) {
1204 if (!thread_safe_sender_.get() || !quota_message_filter_.get())
1205 return;
1206 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(),
1207 quota_message_filter_.get())
1208 ->QueryStorageUsageAndQuota(
1209 storage_partition,
1210 static_cast<storage::StorageType>(type),
1211 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
1214 //------------------------------------------------------------------------------
1216 blink::WebBluetooth* RendererBlinkPlatformImpl::bluetooth() {
1217 return bluetooth_.get();
1220 //------------------------------------------------------------------------------
1222 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1223 const blink::WebBatteryStatus& status) {
1224 if (!g_test_battery_status_listener)
1225 return;
1226 g_test_battery_status_listener->updateBatteryStatus(status);
1229 } // namespace content