cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / renderer / renderer_blink_platform_impl.cc
blob242a5950a3c6cca3b1b844a75efd806d3955dfcf
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/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 "storage/common/quota/quota_types.h"
65 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
66 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
67 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
68 #include "third_party/WebKit/public/platform/WebDeviceMotionListener.h"
69 #include "third_party/WebKit/public/platform/WebDeviceOrientationListener.h"
70 #include "third_party/WebKit/public/platform/WebFileInfo.h"
71 #include "third_party/WebKit/public/platform/WebGamepads.h"
72 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
73 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
74 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
75 #include "third_party/WebKit/public/platform/WebURL.h"
76 #include "third_party/WebKit/public/platform/WebVector.h"
77 #include "ui/gfx/color_profile.h"
78 #include "url/gurl.h"
79 #include "webkit/common/gpu/context_provider_web_context.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 #include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
85 #endif
87 #if defined(OS_MACOSX)
88 #include "content/common/mac/font_descriptor.h"
89 #include "content/common/mac/font_loader.h"
90 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
91 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
92 #endif
94 #if defined(OS_POSIX)
95 #include "base/file_descriptor_posix.h"
96 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
97 #include <map>
98 #include <string>
100 #include "base/synchronization/lock.h"
101 #include "content/common/child_process_sandbox_support_impl_linux.h"
102 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
103 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
104 #include "third_party/icu/source/common/unicode/utf16.h"
105 #endif
106 #endif
108 #if defined(OS_WIN)
109 #include "content/common/child_process_messages.h"
110 #include "third_party/WebKit/public/platform/win/WebSandboxSupport.h"
111 #endif
113 #if defined(USE_AURA)
114 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
115 #elif !defined(OS_MACOSX)
116 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
117 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
118 #endif
120 #if defined(ENABLE_WEBRTC)
121 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
122 #endif
124 using blink::Platform;
125 using blink::WebAudioDevice;
126 using blink::WebBlobRegistry;
127 using blink::WebDatabaseObserver;
128 using blink::WebFileInfo;
129 using blink::WebFileSystem;
130 using blink::WebGamepad;
131 using blink::WebGamepads;
132 using blink::WebIDBFactory;
133 using blink::WebMIDIAccessor;
134 using blink::WebMediaStreamCenter;
135 using blink::WebMediaStreamCenterClient;
136 using blink::WebMimeRegistry;
137 using blink::WebRTCPeerConnectionHandler;
138 using blink::WebRTCPeerConnectionHandlerClient;
139 using blink::WebStorageNamespace;
140 using blink::WebString;
141 using blink::WebURL;
142 using blink::WebVector;
144 namespace content {
146 namespace {
148 bool g_sandbox_enabled = true;
149 double g_test_device_light_data = -1;
150 base::LazyInstance<blink::WebDeviceMotionData>::Leaky
151 g_test_device_motion_data = LAZY_INSTANCE_INITIALIZER;
152 base::LazyInstance<blink::WebDeviceOrientationData>::Leaky
153 g_test_device_orientation_data = LAZY_INSTANCE_INITIALIZER;
155 } // namespace
157 //------------------------------------------------------------------------------
159 class RendererBlinkPlatformImpl::MimeRegistry
160 : public SimpleWebMimeRegistryImpl {
161 public:
162 virtual blink::WebMimeRegistry::SupportsType supportsMediaMIMEType(
163 const blink::WebString& mime_type,
164 const blink::WebString& codecs,
165 const blink::WebString& key_system);
166 virtual bool supportsMediaSourceMIMEType(const blink::WebString& mime_type,
167 const blink::WebString& codecs);
168 virtual bool supportsEncryptedMediaMIMEType(const WebString& key_system,
169 const WebString& mime_type,
170 const WebString& codecs) override;
171 virtual blink::WebString mimeTypeForExtension(
172 const blink::WebString& file_extension);
173 virtual blink::WebString mimeTypeFromFile(
174 const blink::WebString& file_path);
177 class RendererBlinkPlatformImpl::FileUtilities : 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 RendererBlinkPlatformImpl::SandboxSupport {};
191 #else
192 class RendererBlinkPlatformImpl::SandboxSupport
193 : public blink::WebSandboxSupport {
194 public:
195 virtual ~SandboxSupport() {}
197 #if defined(OS_WIN)
198 virtual bool ensureFontLoaded(HFONT);
199 #elif defined(OS_MACOSX)
200 virtual bool loadFont(
201 NSFont* src_font,
202 CGFontRef* container,
203 uint32* font_id);
204 #elif defined(OS_POSIX)
205 virtual void getFallbackFontForCharacter(
206 blink::WebUChar32 character,
207 const char* preferred_locale,
208 blink::WebFallbackFont* fallbackFont);
209 virtual void getRenderStyleForStrike(
210 const char* family, int sizeAndStyle, blink::WebFontRenderStyle* out);
212 private:
213 // WebKit likes to ask us for the correct font family to use for a set of
214 // unicode code points. It needs this information frequently so we cache it
215 // here.
216 base::Lock unicode_font_families_mutex_;
217 std::map<int32_t, blink::WebFallbackFont> unicode_font_families_;
218 #endif
220 #endif // defined(OS_ANDROID)
222 //------------------------------------------------------------------------------
224 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl()
225 : clipboard_client_(new RendererClipboardClient),
226 clipboard_(new WebClipboardImpl(clipboard_client_.get())),
227 mime_registry_(new RendererBlinkPlatformImpl::MimeRegistry),
228 sudden_termination_disables_(0),
229 plugin_refresh_allowed_(true),
230 child_thread_loop_(base::MessageLoopProxy::current()),
231 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl) {
232 if (g_sandbox_enabled && sandboxEnabled()) {
233 sandbox_support_.reset(new RendererBlinkPlatformImpl::SandboxSupport);
234 } else {
235 DVLOG(1) << "Disabling sandbox support for testing.";
238 // ChildThread may not exist in some tests.
239 if (ChildThread::current()) {
240 sync_message_filter_ = ChildThread::current()->sync_message_filter();
241 thread_safe_sender_ = ChildThread::current()->thread_safe_sender();
242 quota_message_filter_ = ChildThread::current()->quota_message_filter();
243 blob_registry_.reset(new WebBlobRegistryImpl(thread_safe_sender_.get()));
244 web_idb_factory_.reset(new WebIDBFactoryImpl(thread_safe_sender_.get()));
245 web_database_observer_impl_.reset(
246 new WebDatabaseObserverImpl(sync_message_filter_.get()));
250 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
251 WebFileSystemImpl::DeleteThreadSpecificInstance();
254 //------------------------------------------------------------------------------
256 blink::WebClipboard* RendererBlinkPlatformImpl::clipboard() {
257 blink::WebClipboard* clipboard =
258 GetContentClient()->renderer()->OverrideWebClipboard();
259 if (clipboard)
260 return clipboard;
261 return clipboard_.get();
264 blink::WebMimeRegistry* RendererBlinkPlatformImpl::mimeRegistry() {
265 return mime_registry_.get();
268 blink::WebFileUtilities* RendererBlinkPlatformImpl::fileUtilities() {
269 if (!file_utilities_) {
270 file_utilities_.reset(new FileUtilities(thread_safe_sender_.get()));
271 file_utilities_->set_sandbox_enabled(sandboxEnabled());
273 return file_utilities_.get();
276 blink::WebSandboxSupport* RendererBlinkPlatformImpl::sandboxSupport() {
277 #if defined(OS_ANDROID)
278 // WebKit doesn't use WebSandboxSupport on android.
279 return NULL;
280 #else
281 return sandbox_support_.get();
282 #endif
285 blink::WebCookieJar* RendererBlinkPlatformImpl::cookieJar() {
286 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
287 return NULL;
290 blink::WebThemeEngine* RendererBlinkPlatformImpl::themeEngine() {
291 blink::WebThemeEngine* theme_engine =
292 GetContentClient()->renderer()->OverrideThemeEngine();
293 if (theme_engine)
294 return theme_engine;
295 return BlinkPlatformImpl::themeEngine();
298 bool RendererBlinkPlatformImpl::sandboxEnabled() {
299 // As explained in Platform.h, this function is used to decide
300 // whether to allow file system operations to come out of WebKit or not.
301 // Even if the sandbox is disabled, there's no reason why the code should
302 // act any differently...unless we're in single process mode. In which
303 // case, we have no other choice. Platform.h discourages using
304 // this switch unless absolutely necessary, so hopefully we won't end up
305 // with too many code paths being different in single-process mode.
306 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);
309 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
310 const char* canonical_url,
311 size_t length) {
312 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url, length);
315 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash) {
316 return GetContentClient()->renderer()->IsLinkVisited(link_hash);
319 void RendererBlinkPlatformImpl::createMessageChannel(
320 blink::WebMessagePortChannel** channel1,
321 blink::WebMessagePortChannel** channel2) {
322 WebMessagePortChannelImpl::CreatePair(
323 child_thread_loop_.get(), channel1, channel2);
326 blink::WebPrescientNetworking*
327 RendererBlinkPlatformImpl::prescientNetworking() {
328 return GetContentClient()->renderer()->GetPrescientNetworking();
331 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL& url,
332 double response_time,
333 const char* data,
334 size_t size) {
335 // Let the browser know we generated cacheable metadata for this resource. The
336 // browser may cache it and return it on subsequent responses to speed
337 // the processing of this resource.
338 std::vector<char> copy(data, data + size);
339 RenderThread::Get()->Send(
340 new ViewHostMsg_DidGenerateCacheableMetadata(url, response_time, copy));
343 WebString RendererBlinkPlatformImpl::defaultLocale() {
344 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
347 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled) {
348 if (enabled) {
349 // We should not get more enables than disables, but we want it to be a
350 // non-fatal error if it does happen.
351 DCHECK_GT(sudden_termination_disables_, 0);
352 sudden_termination_disables_ = std::max(sudden_termination_disables_ - 1,
354 if (sudden_termination_disables_ != 0)
355 return;
356 } else {
357 sudden_termination_disables_++;
358 if (sudden_termination_disables_ != 1)
359 return;
362 RenderThread* thread = RenderThread::Get();
363 if (thread) // NULL in unittests.
364 thread->Send(new ViewHostMsg_SuddenTerminationChanged(enabled));
367 WebStorageNamespace* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
368 return new WebStorageNamespaceImpl();
372 //------------------------------------------------------------------------------
374 WebIDBFactory* RendererBlinkPlatformImpl::idbFactory() {
375 return web_idb_factory_.get();
378 //------------------------------------------------------------------------------
380 WebFileSystem* RendererBlinkPlatformImpl::fileSystem() {
381 return WebFileSystemImpl::ThreadSpecificInstance(child_thread_loop_.get());
384 //------------------------------------------------------------------------------
386 WebMimeRegistry::SupportsType
387 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
388 const WebString& mime_type,
389 const WebString& codecs,
390 const WebString& key_system) {
391 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
392 // Not supporting the container is a flat-out no.
393 if (!net::IsSupportedMediaMimeType(mime_type_ascii))
394 return IsNotSupported;
396 if (!key_system.isEmpty()) {
397 // Check whether the key system is supported with the mime_type and codecs.
399 // Chromium only supports ASCII parameters.
400 if (!base::IsStringASCII(key_system))
401 return IsNotSupported;
403 std::string key_system_ascii =
404 GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system));
405 std::vector<std::string> strict_codecs;
406 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, true);
408 if (!IsSupportedKeySystemWithMediaMimeType(
409 mime_type_ascii, strict_codecs, key_system_ascii)) {
410 return IsNotSupported;
413 // Continue processing the mime_type and codecs.
416 // Check list of strict codecs to see if it is supported.
417 if (net::IsStrictMediaMimeType(mime_type_ascii)) {
418 // Check if the codecs are a perfect match.
419 std::vector<std::string> strict_codecs;
420 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
421 return static_cast<WebMimeRegistry::SupportsType> (
422 net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
425 // If we don't recognize the codec, it's possible we support it.
426 std::vector<std::string> parsed_codecs;
427 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
428 if (!net::AreSupportedMediaCodecs(parsed_codecs))
429 return MayBeSupported;
431 // Otherwise we have a perfect match.
432 return IsSupported;
435 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
436 const blink::WebString& mime_type,
437 const WebString& codecs) {
438 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
439 std::vector<std::string> parsed_codec_ids;
440 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
441 if (mime_type_ascii.empty())
442 return false;
443 return media::StreamParserFactory::IsTypeSupported(
444 mime_type_ascii, parsed_codec_ids);
447 bool RendererBlinkPlatformImpl::MimeRegistry::supportsEncryptedMediaMIMEType(
448 const WebString& key_system,
449 const WebString& mime_type,
450 const WebString& codecs) {
451 // Chromium only supports ASCII parameters.
452 if (!base::IsStringASCII(key_system) || !base::IsStringASCII(mime_type) ||
453 !base::IsStringASCII(codecs)) {
454 return false;
457 if (key_system.isEmpty())
458 return false;
460 const std::string mime_type_ascii = base::UTF16ToASCII(mime_type);
462 std::vector<std::string> codec_vector;
463 bool strip_suffix = !net::IsStrictMediaMimeType(mime_type_ascii);
464 net::ParseCodecString(base::UTF16ToASCII(codecs), &codec_vector,
465 strip_suffix);
467 return IsSupportedKeySystemWithMediaMimeType(
468 mime_type_ascii, codec_vector, base::UTF16ToASCII(key_system));
471 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
472 const WebString& file_extension) {
473 if (IsPluginProcess())
474 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension);
476 // The sandbox restricts our access to the registry, so we need to proxy
477 // these calls over to the browser process.
478 std::string mime_type;
479 RenderThread::Get()->Send(
480 new MimeRegistryMsg_GetMimeTypeFromExtension(
481 base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type));
482 return base::ASCIIToUTF16(mime_type);
485 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
486 const WebString& file_path) {
487 if (IsPluginProcess())
488 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path);
490 // The sandbox restricts our access to the registry, so we need to proxy
491 // these calls over to the browser process.
492 std::string mime_type;
493 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
494 base::FilePath::FromUTF16Unsafe(file_path),
495 &mime_type));
496 return base::ASCIIToUTF16(mime_type);
499 //------------------------------------------------------------------------------
501 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
502 const WebString& path,
503 WebFileInfo& web_file_info) {
504 base::File::Info file_info;
505 base::File::Error status = base::File::FILE_ERROR_MAX;
506 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
507 base::FilePath::FromUTF16Unsafe(path), &file_info, &status)) ||
508 status != base::File::FILE_OK) {
509 return false;
511 FileInfoToWebFileInfo(file_info, &web_file_info);
512 web_file_info.platformPath = path;
513 return true;
516 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
517 IPC::SyncMessage* msg) const {
518 base::TimeTicks begin = base::TimeTicks::Now();
519 const bool success = thread_safe_sender_->Send(msg);
520 base::TimeDelta delta = base::TimeTicks::Now() - begin;
521 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta);
522 return success;
525 //------------------------------------------------------------------------------
527 #if defined(OS_WIN)
529 bool RendererBlinkPlatformImpl::SandboxSupport::ensureFontLoaded(HFONT font) {
530 LOGFONT logfont;
531 GetObject(font, sizeof(LOGFONT), &logfont);
532 RenderThread::Get()->PreCacheFont(logfont);
533 return true;
536 #elif defined(OS_MACOSX)
538 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont* src_font,
539 CGFontRef* out,
540 uint32* font_id) {
541 uint32 font_data_size;
542 FontDescriptor src_font_descriptor(src_font);
543 base::SharedMemoryHandle font_data;
544 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
545 src_font_descriptor, &font_data_size, &font_data, font_id))) {
546 *out = NULL;
547 *font_id = 0;
548 return false;
551 if (font_data_size == 0 || font_data == base::SharedMemory::NULLHandle() ||
552 *font_id == 0) {
553 LOG(ERROR) << "Bad response from ViewHostMsg_LoadFont() for " <<
554 src_font_descriptor.font_name;
555 *out = NULL;
556 *font_id = 0;
557 return false;
560 // TODO(jeremy): Need to call back into WebKit to make sure that the font
561 // isn't already activated, based on the font id. If it's already
562 // activated, don't reactivate it here - crbug.com/72727 .
564 return FontLoader::CGFontRefFromBuffer(font_data, font_data_size, out);
567 #elif defined(OS_ANDROID)
569 // WebKit doesn't use WebSandboxSupport on android so we don't need to
570 // implement anything here. This is cleaner to support than excluding the
571 // whole class for android.
573 #elif defined(OS_POSIX)
575 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
576 blink::WebUChar32 character,
577 const char* preferred_locale,
578 blink::WebFallbackFont* fallbackFont) {
579 base::AutoLock lock(unicode_font_families_mutex_);
580 const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
581 unicode_font_families_.find(character);
582 if (iter != unicode_font_families_.end()) {
583 fallbackFont->name = iter->second.name;
584 fallbackFont->filename = iter->second.filename;
585 fallbackFont->fontconfigInterfaceId = iter->second.fontconfigInterfaceId;
586 fallbackFont->ttcIndex = iter->second.ttcIndex;
587 fallbackFont->isBold = iter->second.isBold;
588 fallbackFont->isItalic = iter->second.isItalic;
589 return;
592 GetFallbackFontForCharacter(character, preferred_locale, fallbackFont);
593 unicode_font_families_.insert(std::make_pair(character, *fallbackFont));
596 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
597 const char* family,
598 int sizeAndStyle,
599 blink::WebFontRenderStyle* out) {
600 GetRenderStyleForStrike(family, sizeAndStyle, out);
603 #endif
605 //------------------------------------------------------------------------------
607 Platform::FileHandle RendererBlinkPlatformImpl::databaseOpenFile(
608 const WebString& vfs_file_name,
609 int desired_flags) {
610 return DatabaseUtil::DatabaseOpenFile(
611 vfs_file_name, desired_flags, sync_message_filter_.get());
614 int RendererBlinkPlatformImpl::databaseDeleteFile(
615 const WebString& vfs_file_name,
616 bool sync_dir) {
617 return DatabaseUtil::DatabaseDeleteFile(
618 vfs_file_name, sync_dir, sync_message_filter_.get());
621 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
622 const WebString& vfs_file_name) {
623 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name,
624 sync_message_filter_.get());
627 long long RendererBlinkPlatformImpl::databaseGetFileSize(
628 const WebString& vfs_file_name) {
629 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name,
630 sync_message_filter_.get());
633 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
634 const WebString& origin_identifier) {
635 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier,
636 sync_message_filter_.get());
639 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
640 RenderThreadImpl* thread = RenderThreadImpl::current();
641 GpuChannelHost* host = thread->EstablishGpuChannelSync(
642 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D);
643 if (!host)
644 return false;
646 return host->gpu_info().SupportsAccelerated2dCanvas();
649 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
650 RenderThreadImpl* thread = RenderThreadImpl::current();
651 // thread can be NULL in tests.
652 return thread && thread->compositor_message_loop_proxy().get();
655 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
656 RenderThreadImpl* thread = RenderThreadImpl::current();
657 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
660 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
661 RenderThreadImpl* thread = RenderThreadImpl::current();
662 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
665 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
666 RenderThreadImpl* thread = RenderThreadImpl::current();
667 return thread->GetAudioHardwareConfig()->GetOutputChannels();
670 WebDatabaseObserver* RendererBlinkPlatformImpl::databaseObserver() {
671 return web_database_observer_impl_.get();
674 WebAudioDevice* RendererBlinkPlatformImpl::createAudioDevice(
675 size_t buffer_size,
676 unsigned input_channels,
677 unsigned channels,
678 double sample_rate,
679 WebAudioDevice::RenderCallback* callback,
680 const blink::WebString& input_device_id) {
681 // Use a mock for testing.
682 blink::WebAudioDevice* mock_device =
683 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate);
684 if (mock_device)
685 return mock_device;
687 // The |channels| does not exactly identify the channel layout of the
688 // device. The switch statement below assigns a best guess to the channel
689 // layout based on number of channels.
690 // TODO(crogers): WebKit should give the channel layout instead of the hard
691 // channel count.
692 media::ChannelLayout layout = media::CHANNEL_LAYOUT_UNSUPPORTED;
693 switch (channels) {
694 case 1:
695 layout = media::CHANNEL_LAYOUT_MONO;
696 break;
697 case 2:
698 layout = media::CHANNEL_LAYOUT_STEREO;
699 break;
700 case 3:
701 layout = media::CHANNEL_LAYOUT_2_1;
702 break;
703 case 4:
704 layout = media::CHANNEL_LAYOUT_4_0;
705 break;
706 case 5:
707 layout = media::CHANNEL_LAYOUT_5_0;
708 break;
709 case 6:
710 layout = media::CHANNEL_LAYOUT_5_1;
711 break;
712 case 7:
713 layout = media::CHANNEL_LAYOUT_7_0;
714 break;
715 case 8:
716 layout = media::CHANNEL_LAYOUT_7_1;
717 break;
718 default:
719 layout = media::CHANNEL_LAYOUT_STEREO;
722 int session_id = 0;
723 if (input_device_id.isNull() ||
724 !base::StringToInt(base::UTF16ToUTF8(input_device_id), &session_id)) {
725 if (input_channels > 0)
726 DLOG(WARNING) << "createAudioDevice(): request for audio input ignored";
728 input_channels = 0;
731 media::AudioParameters params(
732 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
733 layout, static_cast<int>(sample_rate), 16, buffer_size,
734 media::AudioParameters::NO_EFFECTS);
736 return new RendererWebAudioDeviceImpl(params, callback, session_id);
739 #if defined(OS_ANDROID)
740 bool RendererBlinkPlatformImpl::loadAudioResource(
741 blink::WebAudioBus* destination_bus,
742 const char* audio_file_data,
743 size_t data_size) {
744 return DecodeAudioFileData(destination_bus,
745 audio_file_data,
746 data_size,
747 thread_safe_sender_);
749 #else
750 bool RendererBlinkPlatformImpl::loadAudioResource(
751 blink::WebAudioBus* destination_bus,
752 const char* audio_file_data,
753 size_t data_size) {
754 return DecodeAudioFileData(
755 destination_bus, audio_file_data, data_size);
757 #endif // defined(OS_ANDROID)
759 //------------------------------------------------------------------------------
761 blink::WebMIDIAccessor* RendererBlinkPlatformImpl::createMIDIAccessor(
762 blink::WebMIDIAccessorClient* client) {
763 blink::WebMIDIAccessor* accessor =
764 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client);
765 if (accessor)
766 return accessor;
768 return new RendererWebMIDIAccessorImpl(client);
771 void RendererBlinkPlatformImpl::getPluginList(
772 bool refresh,
773 blink::WebPluginListBuilder* builder) {
774 #if defined(ENABLE_PLUGINS)
775 std::vector<WebPluginInfo> plugins;
776 if (!plugin_refresh_allowed_)
777 refresh = false;
778 RenderThread::Get()->Send(
779 new ViewHostMsg_GetPlugins(refresh, &plugins));
780 for (size_t i = 0; i < plugins.size(); ++i) {
781 const WebPluginInfo& plugin = plugins[i];
783 builder->addPlugin(
784 plugin.name, plugin.desc,
785 plugin.path.BaseName().AsUTF16Unsafe());
787 for (size_t j = 0; j < plugin.mime_types.size(); ++j) {
788 const WebPluginMimeType& mime_type = plugin.mime_types[j];
790 builder->addMediaTypeToLastPlugin(
791 WebString::fromUTF8(mime_type.mime_type), mime_type.description);
793 for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
794 builder->addFileExtensionToLastMediaType(
795 WebString::fromUTF8(mime_type.file_extensions[k]));
799 #endif
802 //------------------------------------------------------------------------------
804 blink::WebPublicSuffixList* RendererBlinkPlatformImpl::publicSuffixList() {
805 return &public_suffix_list_;
808 //------------------------------------------------------------------------------
810 blink::WebString RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
811 unsigned key_size_index,
812 const blink::WebString& challenge,
813 const blink::WebURL& url) {
814 std::string signed_public_key;
815 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
816 static_cast<uint32>(key_size_index),
817 challenge.utf8(),
818 GURL(url),
819 &signed_public_key));
820 return WebString::fromUTF8(signed_public_key);
823 //------------------------------------------------------------------------------
825 void RendererBlinkPlatformImpl::screenColorProfile(
826 WebVector<char>* to_profile) {
827 #if defined(OS_WIN)
828 // On Windows screen color profile is only available in the browser.
829 std::vector<char> profile;
830 // This Send() can be called from any impl-side thread. Use a thread
831 // safe send to avoid crashing trying to access RenderThread::Get(),
832 // which is not accessible from arbitrary threads.
833 thread_safe_sender_->Send(
834 new ViewHostMsg_GetMonitorColorProfile(&profile));
835 *to_profile = profile;
836 #else
837 // On other platforms, the primary monitor color profile can be read
838 // directly.
839 gfx::ColorProfile profile;
840 *to_profile = profile.profile();
841 #endif
844 //------------------------------------------------------------------------------
846 blink::WebScrollbarBehavior* RendererBlinkPlatformImpl::scrollbarBehavior() {
847 return web_scrollbar_behavior_.get();
850 //------------------------------------------------------------------------------
852 WebBlobRegistry* RendererBlinkPlatformImpl::blobRegistry() {
853 // blob_registry_ can be NULL when running some tests.
854 return blob_registry_.get();
857 //------------------------------------------------------------------------------
859 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads& gamepads) {
860 PlatformEventObserverBase* observer =
861 platform_event_observers_.Lookup(blink::WebPlatformEventGamepad);
862 if (!observer)
863 return;
864 static_cast<RendererGamepadProvider*>(observer)->SampleGamepads(gamepads);
867 //------------------------------------------------------------------------------
869 WebRTCPeerConnectionHandler*
870 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
871 WebRTCPeerConnectionHandlerClient* client) {
872 RenderThreadImpl* render_thread = RenderThreadImpl::current();
873 DCHECK(render_thread);
874 if (!render_thread)
875 return NULL;
877 #if defined(ENABLE_WEBRTC)
878 WebRTCPeerConnectionHandler* peer_connection_handler =
879 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
880 client);
881 if (peer_connection_handler)
882 return peer_connection_handler;
884 PeerConnectionDependencyFactory* rtc_dependency_factory =
885 render_thread->GetPeerConnectionDependencyFactory();
886 return rtc_dependency_factory->CreateRTCPeerConnectionHandler(client);
887 #else
888 return NULL;
889 #endif // defined(ENABLE_WEBRTC)
892 //------------------------------------------------------------------------------
894 WebMediaStreamCenter* RendererBlinkPlatformImpl::createMediaStreamCenter(
895 WebMediaStreamCenterClient* client) {
896 RenderThreadImpl* render_thread = RenderThreadImpl::current();
897 DCHECK(render_thread);
898 if (!render_thread)
899 return NULL;
900 return render_thread->CreateMediaStreamCenter(client);
903 // static
904 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable) {
905 bool was_enabled = g_sandbox_enabled;
906 g_sandbox_enabled = enable;
907 return was_enabled;
910 //------------------------------------------------------------------------------
912 blink::WebSpeechSynthesizer* RendererBlinkPlatformImpl::createSpeechSynthesizer(
913 blink::WebSpeechSynthesizerClient* client) {
914 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client);
917 //------------------------------------------------------------------------------
919 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
920 size_t* private_bytes,
921 size_t* shared_bytes) {
922 content::RenderThread::Get()->Send(
923 new ViewHostMsg_GetProcessMemorySizes(private_bytes, shared_bytes));
924 return true;
927 //------------------------------------------------------------------------------
929 blink::WebGraphicsContext3D*
930 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
931 const blink::WebGraphicsContext3D::Attributes& attributes) {
932 return createOffscreenGraphicsContext3D(attributes, NULL);
935 blink::WebGraphicsContext3D*
936 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
937 const blink::WebGraphicsContext3D::Attributes& attributes,
938 blink::WebGraphicsContext3D* share_context) {
939 if (!RenderThreadImpl::current())
940 return NULL;
942 #if defined(OS_ANDROID)
943 if (SynchronousCompositorFactory* factory =
944 SynchronousCompositorFactory::GetInstance()) {
945 scoped_ptr<webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl>
946 in_process_context(
947 factory->CreateOffscreenGraphicsContext3D(attributes));
948 if (!in_process_context ||
949 !in_process_context->InitializeOnCurrentThread())
950 return NULL;
951 return in_process_context.release();
953 #endif
955 scoped_refptr<GpuChannelHost> gpu_channel_host(
956 RenderThreadImpl::current()->EstablishGpuChannelSync(
957 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
959 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
960 bool lose_context_when_out_of_memory = false;
961 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
962 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
963 gpu_channel_host.get(),
964 attributes,
965 lose_context_when_out_of_memory,
966 GURL(attributes.topDocumentURL),
967 limits,
968 static_cast<WebGraphicsContext3DCommandBufferImpl*>(share_context)));
970 // Most likely the GPU process exited and the attempt to reconnect to it
971 // failed. Need to try to restore the context again later.
972 if (!context || !context->InitializeOnCurrentThread())
973 return NULL;
974 return context.release();
977 //------------------------------------------------------------------------------
979 blink::WebGraphicsContext3DProvider*
980 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
981 scoped_refptr<webkit::gpu::ContextProviderWebContext> provider =
982 RenderThreadImpl::current()->SharedMainThreadContextProvider();
983 if (!provider.get())
984 return NULL;
985 return new WebGraphicsContext3DProviderImpl(provider);
988 //------------------------------------------------------------------------------
990 blink::WebCompositorSupport* RendererBlinkPlatformImpl::compositorSupport() {
991 return &compositor_support_;
994 //------------------------------------------------------------------------------
996 blink::WebString RendererBlinkPlatformImpl::convertIDNToUnicode(
997 const blink::WebString& host,
998 const blink::WebString& languages) {
999 return net::IDNToUnicode(host.utf8(), languages.utf8());
1002 //------------------------------------------------------------------------------
1004 // static
1005 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data) {
1006 g_test_device_light_data = data;
1009 //------------------------------------------------------------------------------
1011 // static
1012 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1013 const blink::WebDeviceMotionData& data) {
1014 g_test_device_motion_data.Get() = data;
1017 //------------------------------------------------------------------------------
1019 // static
1020 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1021 const blink::WebDeviceOrientationData& data) {
1022 g_test_device_orientation_data.Get() = data;
1025 //------------------------------------------------------------------------------
1027 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds) {
1028 RenderThread::Get()->Send(
1029 new ViewHostMsg_Vibrate(base::checked_cast<int64>(milliseconds)));
1032 void RendererBlinkPlatformImpl::cancelVibration() {
1033 RenderThread::Get()->Send(new ViewHostMsg_CancelVibration());
1036 //------------------------------------------------------------------------------
1038 // static
1039 PlatformEventObserverBase*
1040 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1041 blink::WebPlatformEventType type) {
1042 RenderThread* thread = RenderThreadImpl::current();
1044 // When running layout tests, those observers should not listen to the actual
1045 // hardware changes. In order to make that happen, they will receive a null
1046 // thread.
1047 if (thread && RenderThreadImpl::current()->layout_test_mode())
1048 thread = 0;
1050 switch (type) {
1051 case blink::WebPlatformEventDeviceMotion: {
1052 return new DeviceMotionEventPump(thread);
1054 case blink::WebPlatformEventDeviceOrientation: {
1055 return new DeviceOrientationEventPump(thread);
1057 case blink::WebPlatformEventDeviceLight: {
1058 return new DeviceLightEventPump(thread);
1060 case blink::WebPlatformEventBattery: {
1061 return new BatteryStatusDispatcher(thread);
1063 case blink::WebPlatformEventGamepad:
1064 return new GamepadSharedMemoryReader(thread);
1065 break;
1066 case blink::WebPlatformEventScreenOrientation:
1067 return new ScreenOrientationObserver();
1068 default:
1069 // A default statement is required to prevent compilation errors when Blink
1070 // adds a new type.
1071 VLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1072 "unknown type.";
1075 return 0;
1078 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1079 blink::WebPlatformEventType type,
1080 scoped_ptr<PlatformEventObserverBase> observer) {
1081 if (platform_event_observers_.Lookup(type))
1082 platform_event_observers_.Remove(type);
1083 platform_event_observers_.AddWithID(observer.release(), type);
1086 void RendererBlinkPlatformImpl::startListening(
1087 blink::WebPlatformEventType type,
1088 blink::WebPlatformEventListener* listener) {
1089 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1090 if (!observer) {
1091 observer = CreatePlatformEventObserverFromType(type);
1092 if (!observer)
1093 return;
1094 platform_event_observers_.AddWithID(observer, static_cast<int32>(type));
1096 observer->Start(listener);
1098 // Device events (motion, orientation and light) expect to get an event fired
1099 // as soon as a listener is registered if a fake data was passed before.
1100 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1101 // using this broken pattern.
1102 if (RenderThreadImpl::current() &&
1103 RenderThreadImpl::current()->layout_test_mode() &&
1104 (type == blink::WebPlatformEventDeviceMotion ||
1105 type == blink::WebPlatformEventDeviceOrientation ||
1106 type == blink::WebPlatformEventDeviceLight)) {
1107 SendFakeDeviceEventDataForTesting(type);
1111 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1112 blink::WebPlatformEventType type) {
1113 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1114 CHECK(observer);
1116 void* data = 0;
1118 switch (type) {
1119 case blink::WebPlatformEventDeviceMotion:
1120 if (!(g_test_device_motion_data == 0))
1121 data = &g_test_device_motion_data.Get();
1122 break;
1123 case blink::WebPlatformEventDeviceOrientation:
1124 if (!(g_test_device_orientation_data == 0))
1125 data = &g_test_device_orientation_data.Get();
1126 break;
1127 case blink::WebPlatformEventDeviceLight:
1128 if (g_test_device_light_data >= 0)
1129 data = &g_test_device_light_data;
1130 break;
1131 default:
1132 NOTREACHED();
1133 break;
1136 if (!data)
1137 return;
1139 base::MessageLoopProxy::current()->PostTask(
1140 FROM_HERE,
1141 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting,
1142 base::Unretained(observer), data));
1145 void RendererBlinkPlatformImpl::stopListening(
1146 blink::WebPlatformEventType type) {
1147 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1148 if (!observer)
1149 return;
1150 observer->Stop();
1153 //------------------------------------------------------------------------------
1155 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1156 const blink::WebURL& storage_partition,
1157 blink::WebStorageQuotaType type,
1158 blink::WebStorageQuotaCallbacks callbacks) {
1159 if (!thread_safe_sender_.get() || !quota_message_filter_.get())
1160 return;
1161 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(),
1162 quota_message_filter_.get())
1163 ->QueryStorageUsageAndQuota(
1164 storage_partition,
1165 static_cast<storage::StorageType>(type),
1166 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
1169 //------------------------------------------------------------------------------
1171 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1172 const blink::WebBatteryStatus& status) {
1173 PlatformEventObserverBase* observer =
1174 platform_event_observers_.Lookup(blink::WebPlatformEventBattery);
1175 if (!observer)
1176 return;
1177 observer->SendFakeDataForTesting((void*)&status);
1180 } // namespace content