Reland "Replace Chrome IPC with Mojo IPC for querying BatteryStatus service"
[chromium-blink-merge.git] / content / renderer / renderer_blink_platform_impl.cc
blob93db956a932d39968c77ceb346f84c40f1886321
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;
154 // Set in startListening() when running layout tests, unset in stopListening(),
155 // not owned by us.
156 blink::WebBatteryStatusListener* g_test_battery_status_listener = nullptr;
158 } // namespace
160 //------------------------------------------------------------------------------
162 class RendererBlinkPlatformImpl::MimeRegistry
163 : public SimpleWebMimeRegistryImpl {
164 public:
165 virtual blink::WebMimeRegistry::SupportsType supportsMediaMIMEType(
166 const blink::WebString& mime_type,
167 const blink::WebString& codecs,
168 const blink::WebString& key_system);
169 virtual bool supportsMediaSourceMIMEType(const blink::WebString& mime_type,
170 const blink::WebString& codecs);
171 virtual bool supportsEncryptedMediaMIMEType(const WebString& key_system,
172 const WebString& mime_type,
173 const WebString& codecs) override;
174 virtual blink::WebString mimeTypeForExtension(
175 const blink::WebString& file_extension);
176 virtual blink::WebString mimeTypeFromFile(
177 const blink::WebString& file_path);
180 class RendererBlinkPlatformImpl::FileUtilities : public WebFileUtilitiesImpl {
181 public:
182 explicit FileUtilities(ThreadSafeSender* sender)
183 : thread_safe_sender_(sender) {}
184 virtual bool getFileInfo(const WebString& path, WebFileInfo& result);
185 private:
186 bool SendSyncMessageFromAnyThread(IPC::SyncMessage* msg) const;
187 scoped_refptr<ThreadSafeSender> thread_safe_sender_;
190 #if defined(OS_ANDROID)
191 // WebKit doesn't use WebSandboxSupport on android so we don't need to
192 // implement anything here.
193 class RendererBlinkPlatformImpl::SandboxSupport {};
194 #else
195 class RendererBlinkPlatformImpl::SandboxSupport
196 : public blink::WebSandboxSupport {
197 public:
198 virtual ~SandboxSupport() {}
200 #if defined(OS_WIN)
201 virtual bool ensureFontLoaded(HFONT);
202 #elif defined(OS_MACOSX)
203 virtual bool loadFont(
204 NSFont* src_font,
205 CGFontRef* container,
206 uint32* font_id);
207 #elif defined(OS_POSIX)
208 virtual void getFallbackFontForCharacter(
209 blink::WebUChar32 character,
210 const char* preferred_locale,
211 blink::WebFallbackFont* fallbackFont);
212 virtual void getRenderStyleForStrike(
213 const char* family, int sizeAndStyle, blink::WebFontRenderStyle* out);
215 private:
216 // WebKit likes to ask us for the correct font family to use for a set of
217 // unicode code points. It needs this information frequently so we cache it
218 // here.
219 base::Lock unicode_font_families_mutex_;
220 std::map<int32_t, blink::WebFallbackFont> unicode_font_families_;
221 #endif
223 #endif // defined(OS_ANDROID)
225 //------------------------------------------------------------------------------
227 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl()
228 : clipboard_client_(new RendererClipboardClient),
229 clipboard_(new WebClipboardImpl(clipboard_client_.get())),
230 mime_registry_(new RendererBlinkPlatformImpl::MimeRegistry),
231 sudden_termination_disables_(0),
232 plugin_refresh_allowed_(true),
233 child_thread_loop_(base::MessageLoopProxy::current()),
234 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl) {
235 if (g_sandbox_enabled && sandboxEnabled()) {
236 sandbox_support_.reset(new RendererBlinkPlatformImpl::SandboxSupport);
237 } else {
238 DVLOG(1) << "Disabling sandbox support for testing.";
241 // ChildThread may not exist in some tests.
242 if (ChildThread::current()) {
243 sync_message_filter_ = ChildThread::current()->sync_message_filter();
244 thread_safe_sender_ = ChildThread::current()->thread_safe_sender();
245 quota_message_filter_ = ChildThread::current()->quota_message_filter();
246 blob_registry_.reset(new WebBlobRegistryImpl(thread_safe_sender_.get()));
247 web_idb_factory_.reset(new WebIDBFactoryImpl(thread_safe_sender_.get()));
248 web_database_observer_impl_.reset(
249 new WebDatabaseObserverImpl(sync_message_filter_.get()));
253 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
254 WebFileSystemImpl::DeleteThreadSpecificInstance();
257 //------------------------------------------------------------------------------
259 blink::WebClipboard* RendererBlinkPlatformImpl::clipboard() {
260 blink::WebClipboard* clipboard =
261 GetContentClient()->renderer()->OverrideWebClipboard();
262 if (clipboard)
263 return clipboard;
264 return clipboard_.get();
267 blink::WebMimeRegistry* RendererBlinkPlatformImpl::mimeRegistry() {
268 return mime_registry_.get();
271 blink::WebFileUtilities* RendererBlinkPlatformImpl::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* RendererBlinkPlatformImpl::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* RendererBlinkPlatformImpl::cookieJar() {
289 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
290 return NULL;
293 blink::WebThemeEngine* RendererBlinkPlatformImpl::themeEngine() {
294 blink::WebThemeEngine* theme_engine =
295 GetContentClient()->renderer()->OverrideThemeEngine();
296 if (theme_engine)
297 return theme_engine;
298 return BlinkPlatformImpl::themeEngine();
301 bool RendererBlinkPlatformImpl::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 RendererBlinkPlatformImpl::visitedLinkHash(
313 const char* canonical_url,
314 size_t length) {
315 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url, length);
318 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash) {
319 return GetContentClient()->renderer()->IsLinkVisited(link_hash);
322 void RendererBlinkPlatformImpl::createMessageChannel(
323 blink::WebMessagePortChannel** channel1,
324 blink::WebMessagePortChannel** channel2) {
325 WebMessagePortChannelImpl::CreatePair(
326 child_thread_loop_.get(), channel1, channel2);
329 blink::WebPrescientNetworking*
330 RendererBlinkPlatformImpl::prescientNetworking() {
331 return GetContentClient()->renderer()->GetPrescientNetworking();
334 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL& url,
335 double response_time,
336 const char* data,
337 size_t size) {
338 // Let the browser know we generated cacheable metadata for this resource. The
339 // browser may cache it and return it on subsequent responses to speed
340 // the processing of this resource.
341 std::vector<char> copy(data, data + size);
342 RenderThread::Get()->Send(
343 new ViewHostMsg_DidGenerateCacheableMetadata(url, response_time, copy));
346 WebString RendererBlinkPlatformImpl::defaultLocale() {
347 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
350 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled) {
351 if (enabled) {
352 // We should not get more enables than disables, but we want it to be a
353 // non-fatal error if it does happen.
354 DCHECK_GT(sudden_termination_disables_, 0);
355 sudden_termination_disables_ = std::max(sudden_termination_disables_ - 1,
357 if (sudden_termination_disables_ != 0)
358 return;
359 } else {
360 sudden_termination_disables_++;
361 if (sudden_termination_disables_ != 1)
362 return;
365 RenderThread* thread = RenderThread::Get();
366 if (thread) // NULL in unittests.
367 thread->Send(new ViewHostMsg_SuddenTerminationChanged(enabled));
370 WebStorageNamespace* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
371 return new WebStorageNamespaceImpl();
375 //------------------------------------------------------------------------------
377 WebIDBFactory* RendererBlinkPlatformImpl::idbFactory() {
378 return web_idb_factory_.get();
381 //------------------------------------------------------------------------------
383 WebFileSystem* RendererBlinkPlatformImpl::fileSystem() {
384 return WebFileSystemImpl::ThreadSpecificInstance(child_thread_loop_.get());
387 //------------------------------------------------------------------------------
389 WebMimeRegistry::SupportsType
390 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
391 const WebString& mime_type,
392 const WebString& codecs,
393 const WebString& key_system) {
394 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
395 // Not supporting the container is a flat-out no.
396 if (!net::IsSupportedMediaMimeType(mime_type_ascii))
397 return IsNotSupported;
399 if (!key_system.isEmpty()) {
400 // Check whether the key system is supported with the mime_type and codecs.
402 // Chromium only supports ASCII parameters.
403 if (!base::IsStringASCII(key_system))
404 return IsNotSupported;
406 std::string key_system_ascii =
407 GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system));
408 std::vector<std::string> strict_codecs;
409 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, true);
411 if (!IsSupportedKeySystemWithMediaMimeType(
412 mime_type_ascii, strict_codecs, key_system_ascii)) {
413 return IsNotSupported;
416 // Continue processing the mime_type and codecs.
419 // Check list of strict codecs to see if it is supported.
420 if (net::IsStrictMediaMimeType(mime_type_ascii)) {
421 // Check if the codecs are a perfect match.
422 std::vector<std::string> strict_codecs;
423 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
424 return static_cast<WebMimeRegistry::SupportsType> (
425 net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
428 // If we don't recognize the codec, it's possible we support it.
429 std::vector<std::string> parsed_codecs;
430 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
431 if (!net::AreSupportedMediaCodecs(parsed_codecs))
432 return MayBeSupported;
434 // Otherwise we have a perfect match.
435 return IsSupported;
438 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
439 const blink::WebString& mime_type,
440 const WebString& codecs) {
441 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
442 std::vector<std::string> parsed_codec_ids;
443 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
444 if (mime_type_ascii.empty())
445 return false;
446 return media::StreamParserFactory::IsTypeSupported(
447 mime_type_ascii, parsed_codec_ids);
450 bool RendererBlinkPlatformImpl::MimeRegistry::supportsEncryptedMediaMIMEType(
451 const WebString& key_system,
452 const WebString& mime_type,
453 const WebString& codecs) {
454 // Chromium only supports ASCII parameters.
455 if (!base::IsStringASCII(key_system) || !base::IsStringASCII(mime_type) ||
456 !base::IsStringASCII(codecs)) {
457 return false;
460 if (key_system.isEmpty())
461 return false;
463 const std::string mime_type_ascii = base::UTF16ToASCII(mime_type);
465 std::vector<std::string> codec_vector;
466 bool strip_suffix = !net::IsStrictMediaMimeType(mime_type_ascii);
467 net::ParseCodecString(base::UTF16ToASCII(codecs), &codec_vector,
468 strip_suffix);
470 return IsSupportedKeySystemWithMediaMimeType(
471 mime_type_ascii, codec_vector, base::UTF16ToASCII(key_system));
474 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
475 const WebString& file_extension) {
476 if (IsPluginProcess())
477 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension);
479 // The sandbox restricts our access to the registry, so we need to proxy
480 // these calls over to the browser process.
481 std::string mime_type;
482 RenderThread::Get()->Send(
483 new MimeRegistryMsg_GetMimeTypeFromExtension(
484 base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type));
485 return base::ASCIIToUTF16(mime_type);
488 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
489 const WebString& file_path) {
490 if (IsPluginProcess())
491 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path);
493 // The sandbox restricts our access to the registry, so we need to proxy
494 // these calls over to the browser process.
495 std::string mime_type;
496 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
497 base::FilePath::FromUTF16Unsafe(file_path),
498 &mime_type));
499 return base::ASCIIToUTF16(mime_type);
502 //------------------------------------------------------------------------------
504 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
505 const WebString& path,
506 WebFileInfo& web_file_info) {
507 base::File::Info file_info;
508 base::File::Error status = base::File::FILE_ERROR_MAX;
509 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
510 base::FilePath::FromUTF16Unsafe(path), &file_info, &status)) ||
511 status != base::File::FILE_OK) {
512 return false;
514 FileInfoToWebFileInfo(file_info, &web_file_info);
515 web_file_info.platformPath = path;
516 return true;
519 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
520 IPC::SyncMessage* msg) const {
521 base::TimeTicks begin = base::TimeTicks::Now();
522 const bool success = thread_safe_sender_->Send(msg);
523 base::TimeDelta delta = base::TimeTicks::Now() - begin;
524 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta);
525 return success;
528 //------------------------------------------------------------------------------
530 #if defined(OS_WIN)
532 bool RendererBlinkPlatformImpl::SandboxSupport::ensureFontLoaded(HFONT font) {
533 LOGFONT logfont;
534 GetObject(font, sizeof(LOGFONT), &logfont);
535 RenderThread::Get()->PreCacheFont(logfont);
536 return true;
539 #elif defined(OS_MACOSX)
541 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont* src_font,
542 CGFontRef* out,
543 uint32* font_id) {
544 uint32 font_data_size;
545 FontDescriptor src_font_descriptor(src_font);
546 base::SharedMemoryHandle font_data;
547 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
548 src_font_descriptor, &font_data_size, &font_data, font_id))) {
549 *out = NULL;
550 *font_id = 0;
551 return false;
554 if (font_data_size == 0 || font_data == base::SharedMemory::NULLHandle() ||
555 *font_id == 0) {
556 LOG(ERROR) << "Bad response from ViewHostMsg_LoadFont() for " <<
557 src_font_descriptor.font_name;
558 *out = NULL;
559 *font_id = 0;
560 return false;
563 // TODO(jeremy): Need to call back into WebKit to make sure that the font
564 // isn't already activated, based on the font id. If it's already
565 // activated, don't reactivate it here - crbug.com/72727 .
567 return FontLoader::CGFontRefFromBuffer(font_data, font_data_size, out);
570 #elif defined(OS_ANDROID)
572 // WebKit doesn't use WebSandboxSupport on android so we don't need to
573 // implement anything here. This is cleaner to support than excluding the
574 // whole class for android.
576 #elif defined(OS_POSIX)
578 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
579 blink::WebUChar32 character,
580 const char* preferred_locale,
581 blink::WebFallbackFont* fallbackFont) {
582 base::AutoLock lock(unicode_font_families_mutex_);
583 const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
584 unicode_font_families_.find(character);
585 if (iter != unicode_font_families_.end()) {
586 fallbackFont->name = iter->second.name;
587 fallbackFont->filename = iter->second.filename;
588 fallbackFont->fontconfigInterfaceId = iter->second.fontconfigInterfaceId;
589 fallbackFont->ttcIndex = iter->second.ttcIndex;
590 fallbackFont->isBold = iter->second.isBold;
591 fallbackFont->isItalic = iter->second.isItalic;
592 return;
595 GetFallbackFontForCharacter(character, preferred_locale, fallbackFont);
596 unicode_font_families_.insert(std::make_pair(character, *fallbackFont));
599 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
600 const char* family,
601 int sizeAndStyle,
602 blink::WebFontRenderStyle* out) {
603 GetRenderStyleForStrike(family, sizeAndStyle, out);
606 #endif
608 //------------------------------------------------------------------------------
610 Platform::FileHandle RendererBlinkPlatformImpl::databaseOpenFile(
611 const WebString& vfs_file_name,
612 int desired_flags) {
613 return DatabaseUtil::DatabaseOpenFile(
614 vfs_file_name, desired_flags, sync_message_filter_.get());
617 int RendererBlinkPlatformImpl::databaseDeleteFile(
618 const WebString& vfs_file_name,
619 bool sync_dir) {
620 return DatabaseUtil::DatabaseDeleteFile(
621 vfs_file_name, sync_dir, sync_message_filter_.get());
624 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
625 const WebString& vfs_file_name) {
626 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name,
627 sync_message_filter_.get());
630 long long RendererBlinkPlatformImpl::databaseGetFileSize(
631 const WebString& vfs_file_name) {
632 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name,
633 sync_message_filter_.get());
636 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
637 const WebString& origin_identifier) {
638 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier,
639 sync_message_filter_.get());
642 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
643 RenderThreadImpl* thread = RenderThreadImpl::current();
644 GpuChannelHost* host = thread->EstablishGpuChannelSync(
645 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D);
646 if (!host)
647 return false;
649 return host->gpu_info().SupportsAccelerated2dCanvas();
652 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
653 RenderThreadImpl* thread = RenderThreadImpl::current();
654 // thread can be NULL in tests.
655 return thread && thread->compositor_message_loop_proxy().get();
658 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
659 RenderThreadImpl* thread = RenderThreadImpl::current();
660 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
663 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
664 RenderThreadImpl* thread = RenderThreadImpl::current();
665 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
668 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
669 RenderThreadImpl* thread = RenderThreadImpl::current();
670 return thread->GetAudioHardwareConfig()->GetOutputChannels();
673 WebDatabaseObserver* RendererBlinkPlatformImpl::databaseObserver() {
674 return web_database_observer_impl_.get();
677 WebAudioDevice* RendererBlinkPlatformImpl::createAudioDevice(
678 size_t buffer_size,
679 unsigned input_channels,
680 unsigned channels,
681 double sample_rate,
682 WebAudioDevice::RenderCallback* callback,
683 const blink::WebString& input_device_id) {
684 // Use a mock for testing.
685 blink::WebAudioDevice* mock_device =
686 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate);
687 if (mock_device)
688 return mock_device;
690 // The |channels| does not exactly identify the channel layout of the
691 // device. The switch statement below assigns a best guess to the channel
692 // layout based on number of channels.
693 // TODO(crogers): WebKit should give the channel layout instead of the hard
694 // channel count.
695 media::ChannelLayout layout = media::CHANNEL_LAYOUT_UNSUPPORTED;
696 switch (channels) {
697 case 1:
698 layout = media::CHANNEL_LAYOUT_MONO;
699 break;
700 case 2:
701 layout = media::CHANNEL_LAYOUT_STEREO;
702 break;
703 case 3:
704 layout = media::CHANNEL_LAYOUT_2_1;
705 break;
706 case 4:
707 layout = media::CHANNEL_LAYOUT_4_0;
708 break;
709 case 5:
710 layout = media::CHANNEL_LAYOUT_5_0;
711 break;
712 case 6:
713 layout = media::CHANNEL_LAYOUT_5_1;
714 break;
715 case 7:
716 layout = media::CHANNEL_LAYOUT_7_0;
717 break;
718 case 8:
719 layout = media::CHANNEL_LAYOUT_7_1;
720 break;
721 default:
722 layout = media::CHANNEL_LAYOUT_STEREO;
725 int session_id = 0;
726 if (input_device_id.isNull() ||
727 !base::StringToInt(base::UTF16ToUTF8(input_device_id), &session_id)) {
728 if (input_channels > 0)
729 DLOG(WARNING) << "createAudioDevice(): request for audio input ignored";
731 input_channels = 0;
734 media::AudioParameters params(
735 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
736 layout, static_cast<int>(sample_rate), 16, buffer_size,
737 media::AudioParameters::NO_EFFECTS);
739 return new RendererWebAudioDeviceImpl(params, callback, session_id);
742 #if defined(OS_ANDROID)
743 bool RendererBlinkPlatformImpl::loadAudioResource(
744 blink::WebAudioBus* destination_bus,
745 const char* audio_file_data,
746 size_t data_size) {
747 return DecodeAudioFileData(destination_bus,
748 audio_file_data,
749 data_size,
750 thread_safe_sender_);
752 #else
753 bool RendererBlinkPlatformImpl::loadAudioResource(
754 blink::WebAudioBus* destination_bus,
755 const char* audio_file_data,
756 size_t data_size) {
757 return DecodeAudioFileData(
758 destination_bus, audio_file_data, data_size);
760 #endif // defined(OS_ANDROID)
762 //------------------------------------------------------------------------------
764 blink::WebMIDIAccessor* RendererBlinkPlatformImpl::createMIDIAccessor(
765 blink::WebMIDIAccessorClient* client) {
766 blink::WebMIDIAccessor* accessor =
767 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client);
768 if (accessor)
769 return accessor;
771 return new RendererWebMIDIAccessorImpl(client);
774 void RendererBlinkPlatformImpl::getPluginList(
775 bool refresh,
776 blink::WebPluginListBuilder* builder) {
777 #if defined(ENABLE_PLUGINS)
778 std::vector<WebPluginInfo> plugins;
779 if (!plugin_refresh_allowed_)
780 refresh = false;
781 RenderThread::Get()->Send(
782 new ViewHostMsg_GetPlugins(refresh, &plugins));
783 for (size_t i = 0; i < plugins.size(); ++i) {
784 const WebPluginInfo& plugin = plugins[i];
786 builder->addPlugin(
787 plugin.name, plugin.desc,
788 plugin.path.BaseName().AsUTF16Unsafe());
790 for (size_t j = 0; j < plugin.mime_types.size(); ++j) {
791 const WebPluginMimeType& mime_type = plugin.mime_types[j];
793 builder->addMediaTypeToLastPlugin(
794 WebString::fromUTF8(mime_type.mime_type), mime_type.description);
796 for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
797 builder->addFileExtensionToLastMediaType(
798 WebString::fromUTF8(mime_type.file_extensions[k]));
802 #endif
805 //------------------------------------------------------------------------------
807 blink::WebPublicSuffixList* RendererBlinkPlatformImpl::publicSuffixList() {
808 return &public_suffix_list_;
811 //------------------------------------------------------------------------------
813 blink::WebString RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
814 unsigned key_size_index,
815 const blink::WebString& challenge,
816 const blink::WebURL& url) {
817 std::string signed_public_key;
818 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
819 static_cast<uint32>(key_size_index),
820 challenge.utf8(),
821 GURL(url),
822 &signed_public_key));
823 return WebString::fromUTF8(signed_public_key);
826 //------------------------------------------------------------------------------
828 void RendererBlinkPlatformImpl::screenColorProfile(
829 WebVector<char>* to_profile) {
830 #if defined(OS_WIN)
831 // On Windows screen color profile is only available in the browser.
832 std::vector<char> profile;
833 // This Send() can be called from any impl-side thread. Use a thread
834 // safe send to avoid crashing trying to access RenderThread::Get(),
835 // which is not accessible from arbitrary threads.
836 thread_safe_sender_->Send(
837 new ViewHostMsg_GetMonitorColorProfile(&profile));
838 *to_profile = profile;
839 #else
840 // On other platforms, the primary monitor color profile can be read
841 // directly.
842 gfx::ColorProfile profile;
843 *to_profile = profile.profile();
844 #endif
847 //------------------------------------------------------------------------------
849 blink::WebScrollbarBehavior* RendererBlinkPlatformImpl::scrollbarBehavior() {
850 return web_scrollbar_behavior_.get();
853 //------------------------------------------------------------------------------
855 WebBlobRegistry* RendererBlinkPlatformImpl::blobRegistry() {
856 // blob_registry_ can be NULL when running some tests.
857 return blob_registry_.get();
860 //------------------------------------------------------------------------------
862 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads& gamepads) {
863 PlatformEventObserverBase* observer =
864 platform_event_observers_.Lookup(blink::WebPlatformEventGamepad);
865 if (!observer)
866 return;
867 static_cast<RendererGamepadProvider*>(observer)->SampleGamepads(gamepads);
870 //------------------------------------------------------------------------------
872 WebRTCPeerConnectionHandler*
873 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
874 WebRTCPeerConnectionHandlerClient* client) {
875 RenderThreadImpl* render_thread = RenderThreadImpl::current();
876 DCHECK(render_thread);
877 if (!render_thread)
878 return NULL;
880 #if defined(ENABLE_WEBRTC)
881 WebRTCPeerConnectionHandler* peer_connection_handler =
882 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
883 client);
884 if (peer_connection_handler)
885 return peer_connection_handler;
887 PeerConnectionDependencyFactory* rtc_dependency_factory =
888 render_thread->GetPeerConnectionDependencyFactory();
889 return rtc_dependency_factory->CreateRTCPeerConnectionHandler(client);
890 #else
891 return NULL;
892 #endif // defined(ENABLE_WEBRTC)
895 //------------------------------------------------------------------------------
897 WebMediaStreamCenter* RendererBlinkPlatformImpl::createMediaStreamCenter(
898 WebMediaStreamCenterClient* client) {
899 RenderThreadImpl* render_thread = RenderThreadImpl::current();
900 DCHECK(render_thread);
901 if (!render_thread)
902 return NULL;
903 return render_thread->CreateMediaStreamCenter(client);
906 // static
907 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable) {
908 bool was_enabled = g_sandbox_enabled;
909 g_sandbox_enabled = enable;
910 return was_enabled;
913 //------------------------------------------------------------------------------
915 blink::WebSpeechSynthesizer* RendererBlinkPlatformImpl::createSpeechSynthesizer(
916 blink::WebSpeechSynthesizerClient* client) {
917 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client);
920 //------------------------------------------------------------------------------
922 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
923 size_t* private_bytes,
924 size_t* shared_bytes) {
925 content::RenderThread::Get()->Send(
926 new ViewHostMsg_GetProcessMemorySizes(private_bytes, shared_bytes));
927 return true;
930 //------------------------------------------------------------------------------
932 blink::WebGraphicsContext3D*
933 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
934 const blink::WebGraphicsContext3D::Attributes& attributes) {
935 return createOffscreenGraphicsContext3D(attributes, NULL);
938 blink::WebGraphicsContext3D*
939 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
940 const blink::WebGraphicsContext3D::Attributes& attributes,
941 blink::WebGraphicsContext3D* share_context) {
942 if (!RenderThreadImpl::current())
943 return NULL;
945 #if defined(OS_ANDROID)
946 if (SynchronousCompositorFactory* factory =
947 SynchronousCompositorFactory::GetInstance()) {
948 scoped_ptr<webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl>
949 in_process_context(
950 factory->CreateOffscreenGraphicsContext3D(attributes));
951 if (!in_process_context ||
952 !in_process_context->InitializeOnCurrentThread())
953 return NULL;
954 return in_process_context.release();
956 #endif
958 scoped_refptr<GpuChannelHost> gpu_channel_host(
959 RenderThreadImpl::current()->EstablishGpuChannelSync(
960 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
962 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
963 bool lose_context_when_out_of_memory = false;
964 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
965 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
966 gpu_channel_host.get(),
967 attributes,
968 lose_context_when_out_of_memory,
969 GURL(attributes.topDocumentURL),
970 limits,
971 static_cast<WebGraphicsContext3DCommandBufferImpl*>(share_context)));
973 // Most likely the GPU process exited and the attempt to reconnect to it
974 // failed. Need to try to restore the context again later.
975 if (!context || !context->InitializeOnCurrentThread())
976 return NULL;
977 return context.release();
980 //------------------------------------------------------------------------------
982 blink::WebGraphicsContext3DProvider*
983 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
984 scoped_refptr<webkit::gpu::ContextProviderWebContext> provider =
985 RenderThreadImpl::current()->SharedMainThreadContextProvider();
986 if (!provider.get())
987 return NULL;
988 return new WebGraphicsContext3DProviderImpl(provider);
991 //------------------------------------------------------------------------------
993 blink::WebCompositorSupport* RendererBlinkPlatformImpl::compositorSupport() {
994 return &compositor_support_;
997 //------------------------------------------------------------------------------
999 blink::WebString RendererBlinkPlatformImpl::convertIDNToUnicode(
1000 const blink::WebString& host,
1001 const blink::WebString& languages) {
1002 return net::IDNToUnicode(host.utf8(), languages.utf8());
1005 //------------------------------------------------------------------------------
1007 // static
1008 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data) {
1009 g_test_device_light_data = data;
1012 //------------------------------------------------------------------------------
1014 // static
1015 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1016 const blink::WebDeviceMotionData& data) {
1017 g_test_device_motion_data.Get() = data;
1020 //------------------------------------------------------------------------------
1022 // static
1023 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1024 const blink::WebDeviceOrientationData& data) {
1025 g_test_device_orientation_data.Get() = data;
1028 //------------------------------------------------------------------------------
1030 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds) {
1031 RenderThread::Get()->Send(
1032 new ViewHostMsg_Vibrate(base::checked_cast<int64>(milliseconds)));
1035 void RendererBlinkPlatformImpl::cancelVibration() {
1036 RenderThread::Get()->Send(new ViewHostMsg_CancelVibration());
1039 //------------------------------------------------------------------------------
1041 // static
1042 PlatformEventObserverBase*
1043 RendererBlinkPlatformImpl::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 = NULL;
1053 switch (type) {
1054 case blink::WebPlatformEventDeviceMotion:
1055 return new DeviceMotionEventPump(thread);
1056 case blink::WebPlatformEventDeviceOrientation:
1057 return new DeviceOrientationEventPump(thread);
1058 case blink::WebPlatformEventDeviceLight:
1059 return new DeviceLightEventPump(thread);
1060 case blink::WebPlatformEventGamepad:
1061 return new GamepadSharedMemoryReader(thread);
1062 case blink::WebPlatformEventScreenOrientation:
1063 return new ScreenOrientationObserver();
1064 default:
1065 // A default statement is required to prevent compilation errors when
1066 // Blink adds a new type.
1067 VLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1068 "unknown type.";
1071 return NULL;
1074 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1075 blink::WebPlatformEventType type,
1076 scoped_ptr<PlatformEventObserverBase> observer) {
1077 DCHECK(type != blink::WebPlatformEventBattery);
1079 if (platform_event_observers_.Lookup(type))
1080 platform_event_observers_.Remove(type);
1081 platform_event_observers_.AddWithID(observer.release(), type);
1084 void RendererBlinkPlatformImpl::startListening(
1085 blink::WebPlatformEventType type,
1086 blink::WebPlatformEventListener* listener) {
1087 if (type == blink::WebPlatformEventBattery) {
1088 if (RenderThreadImpl::current() &&
1089 RenderThreadImpl::current()->layout_test_mode()) {
1090 g_test_battery_status_listener =
1091 static_cast<blink::WebBatteryStatusListener*>(listener);
1092 } else {
1093 battery_status_dispatcher_.reset(new BatteryStatusDispatcher(
1094 static_cast<blink::WebBatteryStatusListener*>(listener)));
1096 return;
1099 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1100 if (!observer) {
1101 observer = CreatePlatformEventObserverFromType(type);
1102 if (!observer)
1103 return;
1104 platform_event_observers_.AddWithID(observer, static_cast<int32>(type));
1106 observer->Start(listener);
1108 // Device events (motion, orientation and light) expect to get an event fired
1109 // as soon as a listener is registered if a fake data was passed before.
1110 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1111 // using this broken pattern.
1112 if (RenderThreadImpl::current() &&
1113 RenderThreadImpl::current()->layout_test_mode() &&
1114 (type == blink::WebPlatformEventDeviceMotion ||
1115 type == blink::WebPlatformEventDeviceOrientation ||
1116 type == blink::WebPlatformEventDeviceLight)) {
1117 SendFakeDeviceEventDataForTesting(type);
1121 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1122 blink::WebPlatformEventType type) {
1123 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1124 CHECK(observer);
1126 void* data = 0;
1128 switch (type) {
1129 case blink::WebPlatformEventDeviceMotion:
1130 if (!(g_test_device_motion_data == 0))
1131 data = &g_test_device_motion_data.Get();
1132 break;
1133 case blink::WebPlatformEventDeviceOrientation:
1134 if (!(g_test_device_orientation_data == 0))
1135 data = &g_test_device_orientation_data.Get();
1136 break;
1137 case blink::WebPlatformEventDeviceLight:
1138 if (g_test_device_light_data >= 0)
1139 data = &g_test_device_light_data;
1140 break;
1141 default:
1142 NOTREACHED();
1143 break;
1146 if (!data)
1147 return;
1149 base::MessageLoopProxy::current()->PostTask(
1150 FROM_HERE,
1151 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting,
1152 base::Unretained(observer), data));
1155 void RendererBlinkPlatformImpl::stopListening(
1156 blink::WebPlatformEventType type) {
1157 if (type == blink::WebPlatformEventBattery) {
1158 g_test_battery_status_listener = nullptr;
1159 battery_status_dispatcher_.reset();
1160 return;
1163 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1164 if (!observer)
1165 return;
1166 observer->Stop();
1169 //------------------------------------------------------------------------------
1171 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1172 const blink::WebURL& storage_partition,
1173 blink::WebStorageQuotaType type,
1174 blink::WebStorageQuotaCallbacks callbacks) {
1175 if (!thread_safe_sender_.get() || !quota_message_filter_.get())
1176 return;
1177 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(),
1178 quota_message_filter_.get())
1179 ->QueryStorageUsageAndQuota(
1180 storage_partition,
1181 static_cast<storage::StorageType>(type),
1182 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
1185 //------------------------------------------------------------------------------
1187 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1188 const blink::WebBatteryStatus& status) {
1189 if (!g_test_battery_status_listener)
1190 return;
1191 g_test_battery_status_listener->updateBatteryStatus(status);
1194 } // namespace content