[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / content / renderer / renderer_blink_platform_impl.cc
blobd0c1d8896e3139d8ede669361743f85d252d34ce
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 "cc/blink/context_provider_web_context.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/service_registry.h"
40 #include "content/public/common/webplugininfo.h"
41 #include "content/public/renderer/content_renderer_client.h"
42 #include "content/renderer/battery_status/battery_status_dispatcher.h"
43 #include "content/renderer/device_sensors/device_light_event_pump.h"
44 #include "content/renderer/device_sensors/device_motion_event_pump.h"
45 #include "content/renderer/device_sensors/device_orientation_event_pump.h"
46 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
47 #include "content/renderer/gamepad_shared_memory_reader.h"
48 #include "content/renderer/media/audio_decoder.h"
49 #include "content/renderer/media/renderer_webaudiodevice_impl.h"
50 #include "content/renderer/media/renderer_webmidiaccessor_impl.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_clipboard_delegate.h"
53 #include "content/renderer/scheduler/renderer_scheduler.h"
54 #include "content/renderer/scheduler/web_scheduler_impl.h"
55 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
56 #include "content/renderer/webclipboard_impl.h"
57 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
58 #include "content/renderer/webpublicsuffixlist_impl.h"
59 #include "gpu/config/gpu_info.h"
60 #include "ipc/ipc_sync_message_filter.h"
61 #include "media/audio/audio_output_device.h"
62 #include "media/base/audio_hardware_config.h"
63 #include "media/base/key_systems.h"
64 #include "media/blink/webcontentdecryptionmodule_impl.h"
65 #include "media/filters/stream_parser_factory.h"
66 #include "net/base/mime_util.h"
67 #include "net/base/net_util.h"
68 #include "storage/common/quota/quota_types.h"
69 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
70 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
71 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
72 #include "third_party/WebKit/public/platform/WebDeviceMotionListener.h"
73 #include "third_party/WebKit/public/platform/WebDeviceOrientationListener.h"
74 #include "third_party/WebKit/public/platform/WebFileInfo.h"
75 #include "third_party/WebKit/public/platform/WebGamepads.h"
76 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
77 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
78 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
79 #include "third_party/WebKit/public/platform/WebURL.h"
80 #include "third_party/WebKit/public/platform/WebVector.h"
81 #include "ui/gfx/color_profile.h"
82 #include "url/gurl.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 "gpu/blink/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_delegate_(new RendererClipboardDelegate),
235 clipboard_(new WebClipboardImpl(clipboard_delegate_.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 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl) {
241 if (g_sandbox_enabled && sandboxEnabled()) {
242 sandbox_support_.reset(new RendererBlinkPlatformImpl::SandboxSupport);
243 } else {
244 DVLOG(1) << "Disabling sandbox support for testing.";
247 // ChildThread may not exist in some tests.
248 if (ChildThreadImpl::current()) {
249 sync_message_filter_ = ChildThreadImpl::current()->sync_message_filter();
250 thread_safe_sender_ = ChildThreadImpl::current()->thread_safe_sender();
251 quota_message_filter_ = ChildThreadImpl::current()->quota_message_filter();
252 blob_registry_.reset(new WebBlobRegistryImpl(thread_safe_sender_.get()));
253 web_idb_factory_.reset(new WebIDBFactoryImpl(thread_safe_sender_.get()));
254 web_database_observer_impl_.reset(
255 new WebDatabaseObserverImpl(sync_message_filter_.get()));
259 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
260 WebFileSystemImpl::DeleteThreadSpecificInstance();
263 //------------------------------------------------------------------------------
265 blink::WebScheduler* RendererBlinkPlatformImpl::scheduler() {
266 return web_scheduler_.get();
269 blink::WebClipboard* RendererBlinkPlatformImpl::clipboard() {
270 blink::WebClipboard* clipboard =
271 GetContentClient()->renderer()->OverrideWebClipboard();
272 if (clipboard)
273 return clipboard;
274 return clipboard_.get();
277 blink::WebMimeRegistry* RendererBlinkPlatformImpl::mimeRegistry() {
278 return mime_registry_.get();
281 blink::WebFileUtilities* RendererBlinkPlatformImpl::fileUtilities() {
282 if (!file_utilities_) {
283 file_utilities_.reset(new FileUtilities(thread_safe_sender_.get()));
284 file_utilities_->set_sandbox_enabled(sandboxEnabled());
286 return file_utilities_.get();
289 blink::WebSandboxSupport* RendererBlinkPlatformImpl::sandboxSupport() {
290 #if defined(OS_ANDROID)
291 // WebKit doesn't use WebSandboxSupport on android.
292 return NULL;
293 #else
294 return sandbox_support_.get();
295 #endif
298 blink::WebCookieJar* RendererBlinkPlatformImpl::cookieJar() {
299 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
300 return NULL;
303 blink::WebThemeEngine* RendererBlinkPlatformImpl::themeEngine() {
304 blink::WebThemeEngine* theme_engine =
305 GetContentClient()->renderer()->OverrideThemeEngine();
306 if (theme_engine)
307 return theme_engine;
308 return BlinkPlatformImpl::themeEngine();
311 bool RendererBlinkPlatformImpl::sandboxEnabled() {
312 // As explained in Platform.h, this function is used to decide
313 // whether to allow file system operations to come out of WebKit or not.
314 // Even if the sandbox is disabled, there's no reason why the code should
315 // act any differently...unless we're in single process mode. In which
316 // case, we have no other choice. Platform.h discourages using
317 // this switch unless absolutely necessary, so hopefully we won't end up
318 // with too many code paths being different in single-process mode.
319 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
320 switches::kSingleProcess);
323 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
324 const char* canonical_url,
325 size_t length) {
326 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url, length);
329 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash) {
330 return GetContentClient()->renderer()->IsLinkVisited(link_hash);
333 void RendererBlinkPlatformImpl::createMessageChannel(
334 blink::WebMessagePortChannel** channel1,
335 blink::WebMessagePortChannel** channel2) {
336 WebMessagePortChannelImpl::CreatePair(
337 default_task_runner_, channel1, channel2);
340 blink::WebPrescientNetworking*
341 RendererBlinkPlatformImpl::prescientNetworking() {
342 return GetContentClient()->renderer()->GetPrescientNetworking();
345 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL& url,
346 double response_time,
347 const char* data,
348 size_t size) {
349 // Let the browser know we generated cacheable metadata for this resource. The
350 // browser may cache it and return it on subsequent responses to speed
351 // the processing of this resource.
352 std::vector<char> copy(data, data + size);
353 RenderThread::Get()->Send(
354 new ViewHostMsg_DidGenerateCacheableMetadata(url, response_time, copy));
357 WebString RendererBlinkPlatformImpl::defaultLocale() {
358 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
361 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled) {
362 if (enabled) {
363 // We should not get more enables than disables, but we want it to be a
364 // non-fatal error if it does happen.
365 DCHECK_GT(sudden_termination_disables_, 0);
366 sudden_termination_disables_ = std::max(sudden_termination_disables_ - 1,
368 if (sudden_termination_disables_ != 0)
369 return;
370 } else {
371 sudden_termination_disables_++;
372 if (sudden_termination_disables_ != 1)
373 return;
376 RenderThread* thread = RenderThread::Get();
377 if (thread) // NULL in unittests.
378 thread->Send(new ViewHostMsg_SuddenTerminationChanged(enabled));
381 WebStorageNamespace* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
382 return new WebStorageNamespaceImpl();
386 //------------------------------------------------------------------------------
388 WebIDBFactory* RendererBlinkPlatformImpl::idbFactory() {
389 return web_idb_factory_.get();
392 //------------------------------------------------------------------------------
394 WebFileSystem* RendererBlinkPlatformImpl::fileSystem() {
395 return WebFileSystemImpl::ThreadSpecificInstance(default_task_runner_);
398 //------------------------------------------------------------------------------
400 WebMimeRegistry::SupportsType
401 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
402 const WebString& mime_type,
403 const WebString& codecs,
404 const WebString& key_system) {
405 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
406 // Not supporting the container is a flat-out no.
407 if (!net::IsSupportedMediaMimeType(mime_type_ascii))
408 return IsNotSupported;
410 if (!key_system.isEmpty()) {
411 // Check whether the key system is supported with the mime_type and codecs.
413 // Chromium only supports ASCII parameters.
414 if (!base::IsStringASCII(key_system))
415 return IsNotSupported;
417 std::string key_system_ascii =
418 media::GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system));
419 std::vector<std::string> strict_codecs;
420 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, true);
422 if (!media::IsSupportedKeySystemWithMediaMimeType(
423 mime_type_ascii, strict_codecs, key_system_ascii)) {
424 return IsNotSupported;
427 // Continue processing the mime_type and codecs.
430 // Check list of strict codecs to see if it is supported.
431 if (net::IsStrictMediaMimeType(mime_type_ascii)) {
432 // Check if the codecs are a perfect match.
433 std::vector<std::string> strict_codecs;
434 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
435 return static_cast<WebMimeRegistry::SupportsType> (
436 net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
439 // If we don't recognize the codec, it's possible we support it.
440 std::vector<std::string> parsed_codecs;
441 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
442 if (!net::AreSupportedMediaCodecs(parsed_codecs))
443 return MayBeSupported;
445 // Otherwise we have a perfect match.
446 return IsSupported;
449 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
450 const blink::WebString& mime_type,
451 const WebString& codecs) {
452 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
453 std::vector<std::string> parsed_codec_ids;
454 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
455 if (mime_type_ascii.empty())
456 return false;
457 return media::StreamParserFactory::IsTypeSupported(
458 mime_type_ascii, parsed_codec_ids);
461 bool RendererBlinkPlatformImpl::MimeRegistry::supportsEncryptedMediaMIMEType(
462 const WebString& key_system,
463 const WebString& mime_type,
464 const WebString& codecs) {
465 // Chromium only supports ASCII parameters.
466 if (!base::IsStringASCII(key_system) || !base::IsStringASCII(mime_type) ||
467 !base::IsStringASCII(codecs)) {
468 return false;
471 if (key_system.isEmpty())
472 return false;
474 const std::string mime_type_ascii = base::UTF16ToASCII(mime_type);
476 std::vector<std::string> codec_vector;
477 bool strip_suffix = !net::IsStrictMediaMimeType(mime_type_ascii);
478 net::ParseCodecString(base::UTF16ToASCII(codecs), &codec_vector,
479 strip_suffix);
481 return media::IsSupportedKeySystemWithMediaMimeType(
482 mime_type_ascii, codec_vector, base::UTF16ToASCII(key_system));
485 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
486 const WebString& file_extension) {
487 if (IsPluginProcess())
488 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension);
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(
494 new MimeRegistryMsg_GetMimeTypeFromExtension(
495 base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type));
496 return base::ASCIIToUTF16(mime_type);
499 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
500 const WebString& file_path) {
501 if (IsPluginProcess())
502 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path);
504 // The sandbox restricts our access to the registry, so we need to proxy
505 // these calls over to the browser process.
506 std::string mime_type;
507 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
508 base::FilePath::FromUTF16Unsafe(file_path),
509 &mime_type));
510 return base::ASCIIToUTF16(mime_type);
513 //------------------------------------------------------------------------------
515 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
516 const WebString& path,
517 WebFileInfo& web_file_info) {
518 base::File::Info file_info;
519 base::File::Error status = base::File::FILE_ERROR_MAX;
520 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
521 base::FilePath::FromUTF16Unsafe(path), &file_info, &status)) ||
522 status != base::File::FILE_OK) {
523 return false;
525 FileInfoToWebFileInfo(file_info, &web_file_info);
526 web_file_info.platformPath = path;
527 return true;
530 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
531 IPC::SyncMessage* msg) const {
532 base::TimeTicks begin = base::TimeTicks::Now();
533 const bool success = thread_safe_sender_->Send(msg);
534 base::TimeDelta delta = base::TimeTicks::Now() - begin;
535 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta);
536 return success;
539 //------------------------------------------------------------------------------
541 #if defined(OS_WIN)
543 bool RendererBlinkPlatformImpl::SandboxSupport::ensureFontLoaded(HFONT font) {
544 LOGFONT logfont;
545 GetObject(font, sizeof(LOGFONT), &logfont);
546 RenderThread::Get()->PreCacheFont(logfont);
547 return true;
550 #elif defined(OS_MACOSX)
552 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont* src_font,
553 CGFontRef* out,
554 uint32* font_id) {
555 uint32 font_data_size;
556 FontDescriptor src_font_descriptor(src_font);
557 base::SharedMemoryHandle font_data;
558 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
559 src_font_descriptor, &font_data_size, &font_data, font_id))) {
560 *out = NULL;
561 *font_id = 0;
562 return false;
565 if (font_data_size == 0 || font_data == base::SharedMemory::NULLHandle() ||
566 *font_id == 0) {
567 LOG(ERROR) << "Bad response from ViewHostMsg_LoadFont() for " <<
568 src_font_descriptor.font_name;
569 *out = NULL;
570 *font_id = 0;
571 return false;
574 // TODO(jeremy): Need to call back into WebKit to make sure that the font
575 // isn't already activated, based on the font id. If it's already
576 // activated, don't reactivate it here - crbug.com/72727 .
578 return FontLoader::CGFontRefFromBuffer(font_data, font_data_size, out);
581 #elif defined(OS_ANDROID)
583 // WebKit doesn't use WebSandboxSupport on android so we don't need to
584 // implement anything here. This is cleaner to support than excluding the
585 // whole class for android.
587 #elif defined(OS_POSIX)
589 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
590 blink::WebUChar32 character,
591 const char* preferred_locale,
592 blink::WebFallbackFont* fallbackFont) {
593 base::AutoLock lock(unicode_font_families_mutex_);
594 const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
595 unicode_font_families_.find(character);
596 if (iter != unicode_font_families_.end()) {
597 fallbackFont->name = iter->second.name;
598 fallbackFont->filename = iter->second.filename;
599 fallbackFont->fontconfigInterfaceId = iter->second.fontconfigInterfaceId;
600 fallbackFont->ttcIndex = iter->second.ttcIndex;
601 fallbackFont->isBold = iter->second.isBold;
602 fallbackFont->isItalic = iter->second.isItalic;
603 return;
606 GetFallbackFontForCharacter(character, preferred_locale, fallbackFont);
607 unicode_font_families_.insert(std::make_pair(character, *fallbackFont));
610 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
611 const char* family,
612 int sizeAndStyle,
613 blink::WebFontRenderStyle* out) {
614 GetRenderStyleForStrike(family, sizeAndStyle, out);
617 #endif
619 //------------------------------------------------------------------------------
621 Platform::FileHandle RendererBlinkPlatformImpl::databaseOpenFile(
622 const WebString& vfs_file_name,
623 int desired_flags) {
624 return DatabaseUtil::DatabaseOpenFile(
625 vfs_file_name, desired_flags, sync_message_filter_.get());
628 int RendererBlinkPlatformImpl::databaseDeleteFile(
629 const WebString& vfs_file_name,
630 bool sync_dir) {
631 return DatabaseUtil::DatabaseDeleteFile(
632 vfs_file_name, sync_dir, sync_message_filter_.get());
635 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
636 const WebString& vfs_file_name) {
637 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name,
638 sync_message_filter_.get());
641 long long RendererBlinkPlatformImpl::databaseGetFileSize(
642 const WebString& vfs_file_name) {
643 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name,
644 sync_message_filter_.get());
647 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
648 const WebString& origin_identifier) {
649 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier,
650 sync_message_filter_.get());
653 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
654 RenderThreadImpl* thread = RenderThreadImpl::current();
655 GpuChannelHost* host = thread->EstablishGpuChannelSync(
656 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D);
657 if (!host)
658 return false;
660 return host->gpu_info().SupportsAccelerated2dCanvas();
663 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
664 RenderThreadImpl* thread = RenderThreadImpl::current();
665 // thread can be NULL in tests.
666 return thread && thread->compositor_message_loop_proxy().get();
669 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
670 RenderThreadImpl* thread = RenderThreadImpl::current();
671 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
674 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
675 RenderThreadImpl* thread = RenderThreadImpl::current();
676 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
679 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
680 RenderThreadImpl* thread = RenderThreadImpl::current();
681 return thread->GetAudioHardwareConfig()->GetOutputChannels();
684 WebDatabaseObserver* RendererBlinkPlatformImpl::databaseObserver() {
685 return web_database_observer_impl_.get();
688 WebAudioDevice* RendererBlinkPlatformImpl::createAudioDevice(
689 size_t buffer_size,
690 unsigned input_channels,
691 unsigned channels,
692 double sample_rate,
693 WebAudioDevice::RenderCallback* callback,
694 const blink::WebString& input_device_id) {
695 // Use a mock for testing.
696 blink::WebAudioDevice* mock_device =
697 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate);
698 if (mock_device)
699 return mock_device;
701 // The |channels| does not exactly identify the channel layout of the
702 // device. The switch statement below assigns a best guess to the channel
703 // layout based on number of channels.
704 // TODO(crogers): WebKit should give the channel layout instead of the hard
705 // channel count.
706 media::ChannelLayout layout = media::CHANNEL_LAYOUT_UNSUPPORTED;
707 switch (channels) {
708 case 1:
709 layout = media::CHANNEL_LAYOUT_MONO;
710 break;
711 case 2:
712 layout = media::CHANNEL_LAYOUT_STEREO;
713 break;
714 case 3:
715 layout = media::CHANNEL_LAYOUT_2_1;
716 break;
717 case 4:
718 layout = media::CHANNEL_LAYOUT_4_0;
719 break;
720 case 5:
721 layout = media::CHANNEL_LAYOUT_5_0;
722 break;
723 case 6:
724 layout = media::CHANNEL_LAYOUT_5_1;
725 break;
726 case 7:
727 layout = media::CHANNEL_LAYOUT_7_0;
728 break;
729 case 8:
730 layout = media::CHANNEL_LAYOUT_7_1;
731 break;
732 default:
733 layout = media::CHANNEL_LAYOUT_STEREO;
736 int session_id = 0;
737 if (input_device_id.isNull() ||
738 !base::StringToInt(base::UTF16ToUTF8(input_device_id), &session_id)) {
739 if (input_channels > 0)
740 DLOG(WARNING) << "createAudioDevice(): request for audio input ignored";
742 input_channels = 0;
745 media::AudioParameters params(
746 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
747 layout, static_cast<int>(sample_rate), 16, buffer_size,
748 media::AudioParameters::NO_EFFECTS);
750 return new RendererWebAudioDeviceImpl(params, callback, session_id);
753 #if defined(OS_ANDROID)
754 bool RendererBlinkPlatformImpl::loadAudioResource(
755 blink::WebAudioBus* destination_bus,
756 const char* audio_file_data,
757 size_t data_size) {
758 return DecodeAudioFileData(destination_bus,
759 audio_file_data,
760 data_size,
761 thread_safe_sender_);
763 #else
764 bool RendererBlinkPlatformImpl::loadAudioResource(
765 blink::WebAudioBus* destination_bus,
766 const char* audio_file_data,
767 size_t data_size) {
768 return DecodeAudioFileData(
769 destination_bus, audio_file_data, data_size);
771 #endif // defined(OS_ANDROID)
773 //------------------------------------------------------------------------------
775 blink::WebMIDIAccessor* RendererBlinkPlatformImpl::createMIDIAccessor(
776 blink::WebMIDIAccessorClient* client) {
777 blink::WebMIDIAccessor* accessor =
778 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client);
779 if (accessor)
780 return accessor;
782 return new RendererWebMIDIAccessorImpl(client);
785 void RendererBlinkPlatformImpl::getPluginList(
786 bool refresh,
787 blink::WebPluginListBuilder* builder) {
788 #if defined(ENABLE_PLUGINS)
789 std::vector<WebPluginInfo> plugins;
790 if (!plugin_refresh_allowed_)
791 refresh = false;
792 RenderThread::Get()->Send(
793 new ViewHostMsg_GetPlugins(refresh, &plugins));
794 for (size_t i = 0; i < plugins.size(); ++i) {
795 const WebPluginInfo& plugin = plugins[i];
797 builder->addPlugin(
798 plugin.name, plugin.desc,
799 plugin.path.BaseName().AsUTF16Unsafe());
801 for (size_t j = 0; j < plugin.mime_types.size(); ++j) {
802 const WebPluginMimeType& mime_type = plugin.mime_types[j];
804 builder->addMediaTypeToLastPlugin(
805 WebString::fromUTF8(mime_type.mime_type), mime_type.description);
807 for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
808 builder->addFileExtensionToLastMediaType(
809 WebString::fromUTF8(mime_type.file_extensions[k]));
813 #endif
816 //------------------------------------------------------------------------------
818 blink::WebPublicSuffixList* RendererBlinkPlatformImpl::publicSuffixList() {
819 return &public_suffix_list_;
822 //------------------------------------------------------------------------------
824 blink::WebString RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
825 unsigned key_size_index,
826 const blink::WebString& challenge,
827 const blink::WebURL& url) {
828 std::string signed_public_key;
829 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
830 static_cast<uint32>(key_size_index),
831 challenge.utf8(),
832 GURL(url),
833 &signed_public_key));
834 return WebString::fromUTF8(signed_public_key);
837 //------------------------------------------------------------------------------
839 void RendererBlinkPlatformImpl::screenColorProfile(
840 WebVector<char>* to_profile) {
841 #if defined(OS_WIN)
842 // On Windows screen color profile is only available in the browser.
843 std::vector<char> profile;
844 // This Send() can be called from any impl-side thread. Use a thread
845 // safe send to avoid crashing trying to access RenderThread::Get(),
846 // which is not accessible from arbitrary threads.
847 thread_safe_sender_->Send(
848 new ViewHostMsg_GetMonitorColorProfile(&profile));
849 *to_profile = profile;
850 #else
851 // On other platforms, the primary monitor color profile can be read
852 // directly.
853 gfx::ColorProfile profile;
854 *to_profile = profile.profile();
855 #endif
858 //------------------------------------------------------------------------------
860 blink::WebScrollbarBehavior* RendererBlinkPlatformImpl::scrollbarBehavior() {
861 return web_scrollbar_behavior_.get();
864 //------------------------------------------------------------------------------
866 WebBlobRegistry* RendererBlinkPlatformImpl::blobRegistry() {
867 // blob_registry_ can be NULL when running some tests.
868 return blob_registry_.get();
871 //------------------------------------------------------------------------------
873 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads& gamepads) {
874 PlatformEventObserverBase* observer =
875 platform_event_observers_.Lookup(blink::WebPlatformEventGamepad);
876 if (!observer)
877 return;
878 static_cast<RendererGamepadProvider*>(observer)->SampleGamepads(gamepads);
881 //------------------------------------------------------------------------------
883 WebRTCPeerConnectionHandler*
884 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
885 WebRTCPeerConnectionHandlerClient* client) {
886 RenderThreadImpl* render_thread = RenderThreadImpl::current();
887 DCHECK(render_thread);
888 if (!render_thread)
889 return NULL;
891 #if defined(ENABLE_WEBRTC)
892 WebRTCPeerConnectionHandler* peer_connection_handler =
893 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
894 client);
895 if (peer_connection_handler)
896 return peer_connection_handler;
898 PeerConnectionDependencyFactory* rtc_dependency_factory =
899 render_thread->GetPeerConnectionDependencyFactory();
900 return rtc_dependency_factory->CreateRTCPeerConnectionHandler(client);
901 #else
902 return NULL;
903 #endif // defined(ENABLE_WEBRTC)
906 //------------------------------------------------------------------------------
908 WebMediaStreamCenter* RendererBlinkPlatformImpl::createMediaStreamCenter(
909 WebMediaStreamCenterClient* client) {
910 RenderThreadImpl* render_thread = RenderThreadImpl::current();
911 DCHECK(render_thread);
912 if (!render_thread)
913 return NULL;
914 return render_thread->CreateMediaStreamCenter(client);
917 // static
918 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable) {
919 bool was_enabled = g_sandbox_enabled;
920 g_sandbox_enabled = enable;
921 return was_enabled;
924 //------------------------------------------------------------------------------
926 blink::WebSpeechSynthesizer* RendererBlinkPlatformImpl::createSpeechSynthesizer(
927 blink::WebSpeechSynthesizerClient* client) {
928 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client);
931 //------------------------------------------------------------------------------
933 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
934 size_t* private_bytes,
935 size_t* shared_bytes) {
936 content::RenderThread::Get()->Send(
937 new ViewHostMsg_GetProcessMemorySizes(private_bytes, shared_bytes));
938 return true;
941 //------------------------------------------------------------------------------
943 blink::WebGraphicsContext3D*
944 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
945 const blink::WebGraphicsContext3D::Attributes& attributes) {
946 return createOffscreenGraphicsContext3D(attributes, NULL);
949 blink::WebGraphicsContext3D*
950 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
951 const blink::WebGraphicsContext3D::Attributes& attributes,
952 blink::WebGraphicsContext3D* share_context) {
953 return createOffscreenGraphicsContext3D(attributes, share_context, NULL);
956 blink::WebGraphicsContext3D*
957 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
958 const blink::WebGraphicsContext3D::Attributes& attributes,
959 blink::WebGraphicsContext3D* share_context,
960 blink::WebGLInfo* gl_info) {
961 if (!RenderThreadImpl::current())
962 return NULL;
964 #if defined(OS_ANDROID)
965 if (SynchronousCompositorFactory* factory =
966 SynchronousCompositorFactory::GetInstance()) {
967 scoped_ptr<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl>
968 in_process_context(
969 factory->CreateOffscreenGraphicsContext3D(attributes));
970 if (!in_process_context ||
971 !in_process_context->InitializeOnCurrentThread())
972 return NULL;
973 return in_process_context.release();
975 #endif
977 scoped_refptr<GpuChannelHost> gpu_channel_host(
978 RenderThreadImpl::current()->EstablishGpuChannelSync(
979 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
981 if (gpu_channel_host.get() && gl_info) {
982 const gpu::GPUInfo& gpu_info = gpu_channel_host->gpu_info();
983 gl_info->vendorInfo.assign(blink::WebString::fromUTF8(gpu_info.gl_vendor));
984 gl_info->rendererInfo.assign(
985 blink::WebString::fromUTF8(gpu_info.gl_renderer));
986 gl_info->driverVersion.assign(
987 blink::WebString::fromUTF8(gpu_info.gl_version));
990 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
991 bool lose_context_when_out_of_memory = false;
992 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
993 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
994 gpu_channel_host.get(),
995 attributes,
996 lose_context_when_out_of_memory,
997 GURL(attributes.topDocumentURL),
998 limits,
999 static_cast<WebGraphicsContext3DCommandBufferImpl*>(share_context)));
1001 // Most likely the GPU process exited and the attempt to reconnect to it
1002 // failed. Need to try to restore the context again later.
1003 if (!context || !context->InitializeOnCurrentThread())
1004 return NULL;
1005 return context.release();
1008 //------------------------------------------------------------------------------
1010 blink::WebGraphicsContext3DProvider*
1011 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
1012 scoped_refptr<cc_blink::ContextProviderWebContext> provider =
1013 RenderThreadImpl::current()->SharedMainThreadContextProvider();
1014 if (!provider.get())
1015 return NULL;
1016 return new WebGraphicsContext3DProviderImpl(provider);
1019 //------------------------------------------------------------------------------
1021 blink::WebCompositorSupport* RendererBlinkPlatformImpl::compositorSupport() {
1022 return &compositor_support_;
1025 //------------------------------------------------------------------------------
1027 blink::WebString RendererBlinkPlatformImpl::convertIDNToUnicode(
1028 const blink::WebString& host,
1029 const blink::WebString& languages) {
1030 return net::IDNToUnicode(host.utf8(), languages.utf8());
1033 //------------------------------------------------------------------------------
1035 // static
1036 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data) {
1037 g_test_device_light_data = data;
1040 //------------------------------------------------------------------------------
1042 // static
1043 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1044 const blink::WebDeviceMotionData& data) {
1045 g_test_device_motion_data.Get() = data;
1048 //------------------------------------------------------------------------------
1050 // static
1051 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1052 const blink::WebDeviceOrientationData& data) {
1053 g_test_device_orientation_data.Get() = data;
1056 //------------------------------------------------------------------------------
1058 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds) {
1059 GetConnectedVibrationManagerService()->Vibrate(
1060 base::checked_cast<int64>(milliseconds));
1061 vibration_manager_.reset();
1064 void RendererBlinkPlatformImpl::cancelVibration() {
1065 GetConnectedVibrationManagerService()->Cancel();
1066 vibration_manager_.reset();
1069 device::VibrationManagerPtr&
1070 RendererBlinkPlatformImpl::GetConnectedVibrationManagerService() {
1071 if (!vibration_manager_) {
1072 RenderThread::Get()->GetServiceRegistry()
1073 ->ConnectToRemoteService(&vibration_manager_);
1075 return vibration_manager_;
1078 //------------------------------------------------------------------------------
1080 // static
1081 PlatformEventObserverBase*
1082 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1083 blink::WebPlatformEventType type) {
1084 RenderThread* thread = RenderThreadImpl::current();
1086 // When running layout tests, those observers should not listen to the actual
1087 // hardware changes. In order to make that happen, they will receive a null
1088 // thread.
1089 if (thread && RenderThreadImpl::current()->layout_test_mode())
1090 thread = NULL;
1092 switch (type) {
1093 case blink::WebPlatformEventDeviceMotion:
1094 return new DeviceMotionEventPump(thread);
1095 case blink::WebPlatformEventDeviceOrientation:
1096 return new DeviceOrientationEventPump(thread);
1097 case blink::WebPlatformEventDeviceLight:
1098 return new DeviceLightEventPump(thread);
1099 case blink::WebPlatformEventGamepad:
1100 return new GamepadSharedMemoryReader(thread);
1101 case blink::WebPlatformEventScreenOrientation:
1102 return new ScreenOrientationObserver();
1103 default:
1104 // A default statement is required to prevent compilation errors when
1105 // Blink adds a new type.
1106 DVLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1107 "unknown type.";
1110 return NULL;
1113 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1114 blink::WebPlatformEventType type,
1115 scoped_ptr<PlatformEventObserverBase> observer) {
1116 DCHECK(type != blink::WebPlatformEventBattery);
1118 if (platform_event_observers_.Lookup(type))
1119 platform_event_observers_.Remove(type);
1120 platform_event_observers_.AddWithID(observer.release(), type);
1123 void RendererBlinkPlatformImpl::startListening(
1124 blink::WebPlatformEventType type,
1125 blink::WebPlatformEventListener* listener) {
1126 if (type == blink::WebPlatformEventBattery) {
1127 if (RenderThreadImpl::current() &&
1128 RenderThreadImpl::current()->layout_test_mode()) {
1129 g_test_battery_status_listener =
1130 static_cast<blink::WebBatteryStatusListener*>(listener);
1131 } else {
1132 battery_status_dispatcher_.reset(new BatteryStatusDispatcher(
1133 static_cast<blink::WebBatteryStatusListener*>(listener)));
1135 return;
1138 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1139 if (!observer) {
1140 observer = CreatePlatformEventObserverFromType(type);
1141 if (!observer)
1142 return;
1143 platform_event_observers_.AddWithID(observer, static_cast<int32>(type));
1145 observer->Start(listener);
1147 // Device events (motion, orientation and light) expect to get an event fired
1148 // as soon as a listener is registered if a fake data was passed before.
1149 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1150 // using this broken pattern.
1151 if (RenderThreadImpl::current() &&
1152 RenderThreadImpl::current()->layout_test_mode() &&
1153 (type == blink::WebPlatformEventDeviceMotion ||
1154 type == blink::WebPlatformEventDeviceOrientation ||
1155 type == blink::WebPlatformEventDeviceLight)) {
1156 SendFakeDeviceEventDataForTesting(type);
1160 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1161 blink::WebPlatformEventType type) {
1162 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1163 CHECK(observer);
1165 void* data = 0;
1167 switch (type) {
1168 case blink::WebPlatformEventDeviceMotion:
1169 if (!(g_test_device_motion_data == 0))
1170 data = &g_test_device_motion_data.Get();
1171 break;
1172 case blink::WebPlatformEventDeviceOrientation:
1173 if (!(g_test_device_orientation_data == 0))
1174 data = &g_test_device_orientation_data.Get();
1175 break;
1176 case blink::WebPlatformEventDeviceLight:
1177 if (g_test_device_light_data >= 0)
1178 data = &g_test_device_light_data;
1179 break;
1180 default:
1181 NOTREACHED();
1182 break;
1185 if (!data)
1186 return;
1188 base::MessageLoopProxy::current()->PostTask(
1189 FROM_HERE,
1190 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting,
1191 base::Unretained(observer), data));
1194 void RendererBlinkPlatformImpl::stopListening(
1195 blink::WebPlatformEventType type) {
1196 if (type == blink::WebPlatformEventBattery) {
1197 g_test_battery_status_listener = nullptr;
1198 battery_status_dispatcher_.reset();
1199 return;
1202 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1203 if (!observer)
1204 return;
1205 observer->Stop();
1208 //------------------------------------------------------------------------------
1210 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1211 const blink::WebURL& storage_partition,
1212 blink::WebStorageQuotaType type,
1213 blink::WebStorageQuotaCallbacks callbacks) {
1214 if (!thread_safe_sender_.get() || !quota_message_filter_.get())
1215 return;
1216 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(),
1217 quota_message_filter_.get())
1218 ->QueryStorageUsageAndQuota(
1219 storage_partition,
1220 static_cast<storage::StorageType>(type),
1221 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
1224 //------------------------------------------------------------------------------
1226 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1227 const blink::WebBatteryStatus& status) {
1228 if (!g_test_battery_status_listener)
1229 return;
1230 g_test_battery_status_listener->updateBatteryStatus(status);
1233 } // namespace content