Don't send a SHChangeNotify for creating an app icon when creating a shortcut.
[chromium-blink-merge.git] / content / renderer / renderer_blink_platform_impl.cc
blobbe9b4d6678eb196703c3120ff00c8c708d6c3205
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/scheduler/webthread_impl_for_scheduler.h"
56 #include "content/renderer/screen_orientation/screen_orientation_observer.h"
57 #include "content/renderer/service_worker/webserviceworkercachestorage_impl.h"
58 #include "content/renderer/webclipboard_impl.h"
59 #include "content/renderer/webgraphicscontext3d_provider_impl.h"
60 #include "content/renderer/webpublicsuffixlist_impl.h"
61 #include "gpu/config/gpu_info.h"
62 #include "ipc/ipc_sync_message_filter.h"
63 #include "media/audio/audio_output_device.h"
64 #include "media/base/audio_hardware_config.h"
65 #include "media/base/key_systems.h"
66 #include "media/blink/webcontentdecryptionmodule_impl.h"
67 #include "media/filters/stream_parser_factory.h"
68 #include "net/base/mime_util.h"
69 #include "net/base/net_util.h"
70 #include "storage/common/database/database_identifier.h"
71 #include "storage/common/quota/quota_types.h"
72 #include "third_party/WebKit/public/platform/WebBatteryStatusListener.h"
73 #include "third_party/WebKit/public/platform/WebBlobRegistry.h"
74 #include "third_party/WebKit/public/platform/WebDeviceLightListener.h"
75 #include "third_party/WebKit/public/platform/WebDeviceMotionListener.h"
76 #include "third_party/WebKit/public/platform/WebDeviceOrientationListener.h"
77 #include "third_party/WebKit/public/platform/WebFileInfo.h"
78 #include "third_party/WebKit/public/platform/WebGamepads.h"
79 #include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
80 #include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
81 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
82 #include "third_party/WebKit/public/platform/WebURL.h"
83 #include "third_party/WebKit/public/platform/WebVector.h"
84 #include "ui/gfx/color_profile.h"
85 #include "url/gurl.h"
87 #if defined(OS_ANDROID)
88 #include "content/renderer/android/synchronous_compositor_factory.h"
89 #include "content/renderer/media/android/audio_decoder_android.h"
90 #include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h"
91 #endif
93 #if defined(OS_MACOSX)
94 #include "content/common/mac/font_descriptor.h"
95 #include "content/common/mac/font_loader.h"
96 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
97 #include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
98 #endif
100 #if defined(OS_POSIX)
101 #include "base/file_descriptor_posix.h"
102 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
103 #include <map>
104 #include <string>
106 #include "base/synchronization/lock.h"
107 #include "content/common/child_process_sandbox_support_impl_linux.h"
108 #include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
109 #include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
110 #include "third_party/icu/source/common/unicode/utf16.h"
111 #endif
112 #endif
114 #if defined(OS_WIN)
115 #include "content/common/child_process_messages.h"
116 #endif
118 #if defined(USE_AURA)
119 #include "content/renderer/webscrollbarbehavior_impl_gtkoraura.h"
120 #elif !defined(OS_MACOSX)
121 #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
122 #define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
123 #endif
125 #if defined(ENABLE_WEBRTC)
126 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
127 #endif
129 using blink::Platform;
130 using blink::WebAudioDevice;
131 using blink::WebBlobRegistry;
132 using blink::WebDatabaseObserver;
133 using blink::WebFileInfo;
134 using blink::WebFileSystem;
135 using blink::WebGamepad;
136 using blink::WebGamepads;
137 using blink::WebIDBFactory;
138 using blink::WebMIDIAccessor;
139 using blink::WebMediaStreamCenter;
140 using blink::WebMediaStreamCenterClient;
141 using blink::WebMimeRegistry;
142 using blink::WebRTCPeerConnectionHandler;
143 using blink::WebRTCPeerConnectionHandlerClient;
144 using blink::WebStorageNamespace;
145 using blink::WebString;
146 using blink::WebURL;
147 using blink::WebVector;
149 namespace content {
151 namespace {
153 bool g_sandbox_enabled = true;
154 double g_test_device_light_data = -1;
155 base::LazyInstance<blink::WebDeviceMotionData>::Leaky
156 g_test_device_motion_data = LAZY_INSTANCE_INITIALIZER;
157 base::LazyInstance<blink::WebDeviceOrientationData>::Leaky
158 g_test_device_orientation_data = LAZY_INSTANCE_INITIALIZER;
159 // Set in startListening() when running layout tests, unset in stopListening(),
160 // not owned by us.
161 blink::WebBatteryStatusListener* g_test_battery_status_listener = nullptr;
163 } // namespace
165 //------------------------------------------------------------------------------
167 class RendererBlinkPlatformImpl::MimeRegistry
168 : public SimpleWebMimeRegistryImpl {
169 public:
170 virtual blink::WebMimeRegistry::SupportsType supportsMediaMIMEType(
171 const blink::WebString& mime_type,
172 const blink::WebString& codecs,
173 const blink::WebString& key_system);
174 virtual bool supportsMediaSourceMIMEType(const blink::WebString& mime_type,
175 const blink::WebString& codecs);
176 virtual blink::WebString mimeTypeForExtension(
177 const blink::WebString& file_extension);
178 virtual blink::WebString mimeTypeFromFile(
179 const blink::WebString& file_path);
182 class RendererBlinkPlatformImpl::FileUtilities : public WebFileUtilitiesImpl {
183 public:
184 explicit FileUtilities(ThreadSafeSender* sender)
185 : thread_safe_sender_(sender) {}
186 virtual bool getFileInfo(const WebString& path, WebFileInfo& result);
187 private:
188 bool SendSyncMessageFromAnyThread(IPC::SyncMessage* msg) const;
189 scoped_refptr<ThreadSafeSender> thread_safe_sender_;
192 #if !defined(OS_ANDROID) && !defined(OS_WIN)
193 class RendererBlinkPlatformImpl::SandboxSupport
194 : public blink::WebSandboxSupport {
195 public:
196 virtual ~SandboxSupport() {}
198 #if defined(OS_MACOSX)
199 virtual bool loadFont(
200 NSFont* src_font,
201 CGFontRef* container,
202 uint32* font_id);
203 #elif defined(OS_POSIX)
204 virtual void getFallbackFontForCharacter(
205 blink::WebUChar32 character,
206 const char* preferred_locale,
207 blink::WebFallbackFont* fallbackFont);
208 virtual void getRenderStyleForStrike(
209 const char* family, int sizeAndStyle, blink::WebFontRenderStyle* out);
211 private:
212 // WebKit likes to ask us for the correct font family to use for a set of
213 // unicode code points. It needs this information frequently so we cache it
214 // here.
215 base::Lock unicode_font_families_mutex_;
216 std::map<int32_t, blink::WebFallbackFont> unicode_font_families_;
217 #endif
219 #endif // !defined(OS_ANDROID) && !defined(OS_WIN)
221 //------------------------------------------------------------------------------
223 RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
224 RendererScheduler* renderer_scheduler)
225 : BlinkPlatformImpl(renderer_scheduler->DefaultTaskRunner()),
226 web_scheduler_(new WebSchedulerImpl(renderer_scheduler)),
227 main_thread_(new WebThreadImplForScheduler(renderer_scheduler)),
228 clipboard_delegate_(new RendererClipboardDelegate),
229 clipboard_(new WebClipboardImpl(clipboard_delegate_.get())),
230 mime_registry_(new RendererBlinkPlatformImpl::MimeRegistry),
231 sudden_termination_disables_(0),
232 plugin_refresh_allowed_(true),
233 default_task_runner_(renderer_scheduler->DefaultTaskRunner()),
234 web_scrollbar_behavior_(new WebScrollbarBehaviorImpl) {
235 #if !defined(OS_ANDROID) && !defined(OS_WIN)
236 if (g_sandbox_enabled && sandboxEnabled()) {
237 sandbox_support_.reset(new RendererBlinkPlatformImpl::SandboxSupport);
238 } else {
239 DVLOG(1) << "Disabling sandbox support for testing.";
241 #endif
243 // ChildThread may not exist in some tests.
244 if (ChildThreadImpl::current()) {
245 sync_message_filter_ = ChildThreadImpl::current()->sync_message_filter();
246 thread_safe_sender_ = ChildThreadImpl::current()->thread_safe_sender();
247 quota_message_filter_ = ChildThreadImpl::current()->quota_message_filter();
248 blob_registry_.reset(new WebBlobRegistryImpl(thread_safe_sender_.get()));
249 web_idb_factory_.reset(new WebIDBFactoryImpl(thread_safe_sender_.get()));
250 web_database_observer_impl_.reset(
251 new WebDatabaseObserverImpl(sync_message_filter_.get()));
255 RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
256 WebFileSystemImpl::DeleteThreadSpecificInstance();
259 //------------------------------------------------------------------------------
261 blink::WebScheduler* RendererBlinkPlatformImpl::scheduler() {
262 return web_scheduler_.get();
265 blink::WebThread* RendererBlinkPlatformImpl::currentThread() {
266 if (main_thread_->isCurrentThread())
267 return main_thread_.get();
268 return BlinkPlatformImpl::currentThread();
271 blink::WebClipboard* RendererBlinkPlatformImpl::clipboard() {
272 blink::WebClipboard* clipboard =
273 GetContentClient()->renderer()->OverrideWebClipboard();
274 if (clipboard)
275 return clipboard;
276 return clipboard_.get();
279 blink::WebMimeRegistry* RendererBlinkPlatformImpl::mimeRegistry() {
280 return mime_registry_.get();
283 blink::WebFileUtilities* RendererBlinkPlatformImpl::fileUtilities() {
284 if (!file_utilities_) {
285 file_utilities_.reset(new FileUtilities(thread_safe_sender_.get()));
286 file_utilities_->set_sandbox_enabled(sandboxEnabled());
288 return file_utilities_.get();
291 blink::WebSandboxSupport* RendererBlinkPlatformImpl::sandboxSupport() {
292 #if defined(OS_ANDROID) || defined(OS_WIN)
293 // These platforms do not require sandbox support.
294 return NULL;
295 #else
296 return sandbox_support_.get();
297 #endif
300 blink::WebCookieJar* RendererBlinkPlatformImpl::cookieJar() {
301 NOTREACHED() << "Use WebFrameClient::cookieJar() instead!";
302 return NULL;
305 blink::WebThemeEngine* RendererBlinkPlatformImpl::themeEngine() {
306 blink::WebThemeEngine* theme_engine =
307 GetContentClient()->renderer()->OverrideThemeEngine();
308 if (theme_engine)
309 return theme_engine;
310 return BlinkPlatformImpl::themeEngine();
313 bool RendererBlinkPlatformImpl::sandboxEnabled() {
314 // As explained in Platform.h, this function is used to decide
315 // whether to allow file system operations to come out of WebKit or not.
316 // Even if the sandbox is disabled, there's no reason why the code should
317 // act any differently...unless we're in single process mode. In which
318 // case, we have no other choice. Platform.h discourages using
319 // this switch unless absolutely necessary, so hopefully we won't end up
320 // with too many code paths being different in single-process mode.
321 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
322 switches::kSingleProcess);
325 unsigned long long RendererBlinkPlatformImpl::visitedLinkHash(
326 const char* canonical_url,
327 size_t length) {
328 return GetContentClient()->renderer()->VisitedLinkHash(canonical_url, length);
331 bool RendererBlinkPlatformImpl::isLinkVisited(unsigned long long link_hash) {
332 return GetContentClient()->renderer()->IsLinkVisited(link_hash);
335 void RendererBlinkPlatformImpl::createMessageChannel(
336 blink::WebMessagePortChannel** channel1,
337 blink::WebMessagePortChannel** channel2) {
338 WebMessagePortChannelImpl::CreatePair(
339 default_task_runner_, channel1, channel2);
342 blink::WebPrescientNetworking*
343 RendererBlinkPlatformImpl::prescientNetworking() {
344 return GetContentClient()->renderer()->GetPrescientNetworking();
347 void RendererBlinkPlatformImpl::cacheMetadata(const blink::WebURL& url,
348 int64 response_time,
349 const char* data,
350 size_t size) {
351 // Let the browser know we generated cacheable metadata for this resource. The
352 // browser may cache it and return it on subsequent responses to speed
353 // the processing of this resource.
354 std::vector<char> copy(data, data + size);
355 RenderThread::Get()->Send(new ViewHostMsg_DidGenerateCacheableMetadata(
356 url, base::Time::FromInternalValue(response_time), copy));
359 WebString RendererBlinkPlatformImpl::defaultLocale() {
360 return base::ASCIIToUTF16(RenderThread::Get()->GetLocale());
363 void RendererBlinkPlatformImpl::suddenTerminationChanged(bool enabled) {
364 if (enabled) {
365 // We should not get more enables than disables, but we want it to be a
366 // non-fatal error if it does happen.
367 DCHECK_GT(sudden_termination_disables_, 0);
368 sudden_termination_disables_ = std::max(sudden_termination_disables_ - 1,
370 if (sudden_termination_disables_ != 0)
371 return;
372 } else {
373 sudden_termination_disables_++;
374 if (sudden_termination_disables_ != 1)
375 return;
378 RenderThread* thread = RenderThread::Get();
379 if (thread) // NULL in unittests.
380 thread->Send(new ViewHostMsg_SuddenTerminationChanged(enabled));
383 WebStorageNamespace* RendererBlinkPlatformImpl::createLocalStorageNamespace() {
384 return new WebStorageNamespaceImpl();
388 //------------------------------------------------------------------------------
390 WebIDBFactory* RendererBlinkPlatformImpl::idbFactory() {
391 return web_idb_factory_.get();
394 //------------------------------------------------------------------------------
396 blink::WebServiceWorkerCacheStorage* RendererBlinkPlatformImpl::cacheStorage(
397 const WebString& origin_identifier) {
398 const GURL origin =
399 storage::GetOriginFromIdentifier(origin_identifier.utf8());
400 return new WebServiceWorkerCacheStorageImpl(thread_safe_sender_.get(),
401 origin);
404 //------------------------------------------------------------------------------
406 WebFileSystem* RendererBlinkPlatformImpl::fileSystem() {
407 return WebFileSystemImpl::ThreadSpecificInstance(default_task_runner_);
410 //------------------------------------------------------------------------------
412 WebMimeRegistry::SupportsType
413 RendererBlinkPlatformImpl::MimeRegistry::supportsMediaMIMEType(
414 const WebString& mime_type,
415 const WebString& codecs,
416 const WebString& key_system) {
417 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
418 // Not supporting the container is a flat-out no.
419 if (!net::IsSupportedMediaMimeType(mime_type_ascii))
420 return IsNotSupported;
422 if (!key_system.isEmpty()) {
423 // Check whether the key system is supported with the mime_type and codecs.
425 // Chromium only supports ASCII parameters.
426 if (!base::IsStringASCII(key_system))
427 return IsNotSupported;
429 std::string key_system_ascii =
430 media::GetUnprefixedKeySystemName(base::UTF16ToASCII(key_system));
431 std::vector<std::string> strict_codecs;
432 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, true);
434 if (!media::PrefixedIsSupportedKeySystemWithMediaMimeType(
435 mime_type_ascii, strict_codecs, key_system_ascii)) {
436 return IsNotSupported;
439 // Continue processing the mime_type and codecs.
442 // Check list of strict codecs to see if it is supported.
443 if (net::IsStrictMediaMimeType(mime_type_ascii)) {
444 // Check if the codecs are a perfect match.
445 std::vector<std::string> strict_codecs;
446 net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
447 return static_cast<WebMimeRegistry::SupportsType> (
448 net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
451 // If we don't recognize the codec, it's possible we support it.
452 std::vector<std::string> parsed_codecs;
453 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
454 if (!net::AreSupportedMediaCodecs(parsed_codecs))
455 return MayBeSupported;
457 // Otherwise we have a perfect match.
458 return IsSupported;
461 bool RendererBlinkPlatformImpl::MimeRegistry::supportsMediaSourceMIMEType(
462 const blink::WebString& mime_type,
463 const WebString& codecs) {
464 const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
465 std::vector<std::string> parsed_codec_ids;
466 net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
467 if (mime_type_ascii.empty())
468 return false;
469 return media::StreamParserFactory::IsTypeSupported(
470 mime_type_ascii, parsed_codec_ids);
473 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeForExtension(
474 const WebString& file_extension) {
475 if (IsPluginProcess())
476 return SimpleWebMimeRegistryImpl::mimeTypeForExtension(file_extension);
478 // The sandbox restricts our access to the registry, so we need to proxy
479 // these calls over to the browser process.
480 std::string mime_type;
481 RenderThread::Get()->Send(
482 new MimeRegistryMsg_GetMimeTypeFromExtension(
483 base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type));
484 return base::ASCIIToUTF16(mime_type);
487 WebString RendererBlinkPlatformImpl::MimeRegistry::mimeTypeFromFile(
488 const WebString& file_path) {
489 if (IsPluginProcess())
490 return SimpleWebMimeRegistryImpl::mimeTypeFromFile(file_path);
492 // The sandbox restricts our access to the registry, so we need to proxy
493 // these calls over to the browser process.
494 std::string mime_type;
495 RenderThread::Get()->Send(new MimeRegistryMsg_GetMimeTypeFromFile(
496 base::FilePath::FromUTF16Unsafe(file_path),
497 &mime_type));
498 return base::ASCIIToUTF16(mime_type);
501 //------------------------------------------------------------------------------
503 bool RendererBlinkPlatformImpl::FileUtilities::getFileInfo(
504 const WebString& path,
505 WebFileInfo& web_file_info) {
506 base::File::Info file_info;
507 base::File::Error status = base::File::FILE_ERROR_MAX;
508 if (!SendSyncMessageFromAnyThread(new FileUtilitiesMsg_GetFileInfo(
509 base::FilePath::FromUTF16Unsafe(path), &file_info, &status)) ||
510 status != base::File::FILE_OK) {
511 return false;
513 FileInfoToWebFileInfo(file_info, &web_file_info);
514 web_file_info.platformPath = path;
515 return true;
518 bool RendererBlinkPlatformImpl::FileUtilities::SendSyncMessageFromAnyThread(
519 IPC::SyncMessage* msg) const {
520 base::TimeTicks begin = base::TimeTicks::Now();
521 const bool success = thread_safe_sender_->Send(msg);
522 base::TimeDelta delta = base::TimeTicks::Now() - begin;
523 UMA_HISTOGRAM_TIMES("RendererSyncIPC.ElapsedTime", delta);
524 return success;
527 //------------------------------------------------------------------------------
529 #if defined(OS_MACOSX)
531 bool RendererBlinkPlatformImpl::SandboxSupport::loadFont(NSFont* src_font,
532 CGFontRef* out,
533 uint32* font_id) {
534 uint32 font_data_size;
535 FontDescriptor src_font_descriptor(src_font);
536 base::SharedMemoryHandle font_data;
537 if (!RenderThread::Get()->Send(new ViewHostMsg_LoadFont(
538 src_font_descriptor, &font_data_size, &font_data, font_id))) {
539 *out = NULL;
540 *font_id = 0;
541 return false;
544 if (font_data_size == 0 || font_data == base::SharedMemory::NULLHandle() ||
545 *font_id == 0) {
546 LOG(ERROR) << "Bad response from ViewHostMsg_LoadFont() for " <<
547 src_font_descriptor.font_name;
548 *out = NULL;
549 *font_id = 0;
550 return false;
553 // TODO(jeremy): Need to call back into WebKit to make sure that the font
554 // isn't already activated, based on the font id. If it's already
555 // activated, don't reactivate it here - crbug.com/72727 .
557 return FontLoader::CGFontRefFromBuffer(font_data, font_data_size, out);
560 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
562 void RendererBlinkPlatformImpl::SandboxSupport::getFallbackFontForCharacter(
563 blink::WebUChar32 character,
564 const char* preferred_locale,
565 blink::WebFallbackFont* fallbackFont) {
566 base::AutoLock lock(unicode_font_families_mutex_);
567 const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
568 unicode_font_families_.find(character);
569 if (iter != unicode_font_families_.end()) {
570 fallbackFont->name = iter->second.name;
571 fallbackFont->filename = iter->second.filename;
572 fallbackFont->fontconfigInterfaceId = iter->second.fontconfigInterfaceId;
573 fallbackFont->ttcIndex = iter->second.ttcIndex;
574 fallbackFont->isBold = iter->second.isBold;
575 fallbackFont->isItalic = iter->second.isItalic;
576 return;
579 GetFallbackFontForCharacter(character, preferred_locale, fallbackFont);
580 unicode_font_families_.insert(std::make_pair(character, *fallbackFont));
583 void RendererBlinkPlatformImpl::SandboxSupport::getRenderStyleForStrike(
584 const char* family,
585 int sizeAndStyle,
586 blink::WebFontRenderStyle* out) {
587 GetRenderStyleForStrike(family, sizeAndStyle, out);
590 #endif
592 //------------------------------------------------------------------------------
594 Platform::FileHandle RendererBlinkPlatformImpl::databaseOpenFile(
595 const WebString& vfs_file_name,
596 int desired_flags) {
597 return DatabaseUtil::DatabaseOpenFile(
598 vfs_file_name, desired_flags, sync_message_filter_.get());
601 int RendererBlinkPlatformImpl::databaseDeleteFile(
602 const WebString& vfs_file_name,
603 bool sync_dir) {
604 return DatabaseUtil::DatabaseDeleteFile(
605 vfs_file_name, sync_dir, sync_message_filter_.get());
608 long RendererBlinkPlatformImpl::databaseGetFileAttributes(
609 const WebString& vfs_file_name) {
610 return DatabaseUtil::DatabaseGetFileAttributes(vfs_file_name,
611 sync_message_filter_.get());
614 long long RendererBlinkPlatformImpl::databaseGetFileSize(
615 const WebString& vfs_file_name) {
616 return DatabaseUtil::DatabaseGetFileSize(vfs_file_name,
617 sync_message_filter_.get());
620 long long RendererBlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
621 const WebString& origin_identifier) {
622 return DatabaseUtil::DatabaseGetSpaceAvailable(origin_identifier,
623 sync_message_filter_.get());
626 bool RendererBlinkPlatformImpl::canAccelerate2dCanvas() {
627 RenderThreadImpl* thread = RenderThreadImpl::current();
628 GpuChannelHost* host = thread->EstablishGpuChannelSync(
629 CAUSE_FOR_GPU_LAUNCH_CANVAS_2D);
630 if (!host)
631 return false;
633 return host->gpu_info().SupportsAccelerated2dCanvas();
636 bool RendererBlinkPlatformImpl::isThreadedCompositingEnabled() {
637 RenderThreadImpl* thread = RenderThreadImpl::current();
638 // thread can be NULL in tests.
639 return thread && thread->compositor_message_loop_proxy().get();
642 double RendererBlinkPlatformImpl::audioHardwareSampleRate() {
643 RenderThreadImpl* thread = RenderThreadImpl::current();
644 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
647 size_t RendererBlinkPlatformImpl::audioHardwareBufferSize() {
648 RenderThreadImpl* thread = RenderThreadImpl::current();
649 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
652 unsigned RendererBlinkPlatformImpl::audioHardwareOutputChannels() {
653 RenderThreadImpl* thread = RenderThreadImpl::current();
654 return thread->GetAudioHardwareConfig()->GetOutputChannels();
657 WebDatabaseObserver* RendererBlinkPlatformImpl::databaseObserver() {
658 return web_database_observer_impl_.get();
661 WebAudioDevice* RendererBlinkPlatformImpl::createAudioDevice(
662 size_t buffer_size,
663 unsigned input_channels,
664 unsigned channels,
665 double sample_rate,
666 WebAudioDevice::RenderCallback* callback,
667 const blink::WebString& input_device_id) {
668 // Use a mock for testing.
669 blink::WebAudioDevice* mock_device =
670 GetContentClient()->renderer()->OverrideCreateAudioDevice(sample_rate);
671 if (mock_device)
672 return mock_device;
674 // The |channels| does not exactly identify the channel layout of the
675 // device. The switch statement below assigns a best guess to the channel
676 // layout based on number of channels.
677 // TODO(crogers): WebKit should give the channel layout instead of the hard
678 // channel count.
679 media::ChannelLayout layout = media::CHANNEL_LAYOUT_UNSUPPORTED;
680 switch (channels) {
681 case 1:
682 layout = media::CHANNEL_LAYOUT_MONO;
683 break;
684 case 2:
685 layout = media::CHANNEL_LAYOUT_STEREO;
686 break;
687 case 3:
688 layout = media::CHANNEL_LAYOUT_2_1;
689 break;
690 case 4:
691 layout = media::CHANNEL_LAYOUT_4_0;
692 break;
693 case 5:
694 layout = media::CHANNEL_LAYOUT_5_0;
695 break;
696 case 6:
697 layout = media::CHANNEL_LAYOUT_5_1;
698 break;
699 case 7:
700 layout = media::CHANNEL_LAYOUT_7_0;
701 break;
702 case 8:
703 layout = media::CHANNEL_LAYOUT_7_1;
704 break;
705 default:
706 layout = media::CHANNEL_LAYOUT_STEREO;
709 int session_id = 0;
710 if (input_device_id.isNull() ||
711 !base::StringToInt(base::UTF16ToUTF8(input_device_id), &session_id)) {
712 if (input_channels > 0)
713 DLOG(WARNING) << "createAudioDevice(): request for audio input ignored";
715 input_channels = 0;
718 media::AudioParameters params(
719 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
720 layout, static_cast<int>(sample_rate), 16, buffer_size,
721 media::AudioParameters::NO_EFFECTS);
723 return new RendererWebAudioDeviceImpl(params, callback, session_id);
726 #if defined(OS_ANDROID)
727 bool RendererBlinkPlatformImpl::loadAudioResource(
728 blink::WebAudioBus* destination_bus,
729 const char* audio_file_data,
730 size_t data_size) {
731 return DecodeAudioFileData(destination_bus,
732 audio_file_data,
733 data_size,
734 thread_safe_sender_);
736 #else
737 bool RendererBlinkPlatformImpl::loadAudioResource(
738 blink::WebAudioBus* destination_bus,
739 const char* audio_file_data,
740 size_t data_size) {
741 return DecodeAudioFileData(
742 destination_bus, audio_file_data, data_size);
744 #endif // defined(OS_ANDROID)
746 //------------------------------------------------------------------------------
748 blink::WebMIDIAccessor* RendererBlinkPlatformImpl::createMIDIAccessor(
749 blink::WebMIDIAccessorClient* client) {
750 blink::WebMIDIAccessor* accessor =
751 GetContentClient()->renderer()->OverrideCreateMIDIAccessor(client);
752 if (accessor)
753 return accessor;
755 return new RendererWebMIDIAccessorImpl(client);
758 void RendererBlinkPlatformImpl::getPluginList(
759 bool refresh,
760 blink::WebPluginListBuilder* builder) {
761 #if defined(ENABLE_PLUGINS)
762 std::vector<WebPluginInfo> plugins;
763 if (!plugin_refresh_allowed_)
764 refresh = false;
765 RenderThread::Get()->Send(
766 new ViewHostMsg_GetPlugins(refresh, &plugins));
767 for (size_t i = 0; i < plugins.size(); ++i) {
768 const WebPluginInfo& plugin = plugins[i];
770 builder->addPlugin(
771 plugin.name, plugin.desc,
772 plugin.path.BaseName().AsUTF16Unsafe());
774 for (size_t j = 0; j < plugin.mime_types.size(); ++j) {
775 const WebPluginMimeType& mime_type = plugin.mime_types[j];
777 builder->addMediaTypeToLastPlugin(
778 WebString::fromUTF8(mime_type.mime_type), mime_type.description);
780 for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
781 builder->addFileExtensionToLastMediaType(
782 WebString::fromUTF8(mime_type.file_extensions[k]));
786 #endif
789 //------------------------------------------------------------------------------
791 blink::WebPublicSuffixList* RendererBlinkPlatformImpl::publicSuffixList() {
792 return &public_suffix_list_;
795 //------------------------------------------------------------------------------
797 blink::WebString RendererBlinkPlatformImpl::signedPublicKeyAndChallengeString(
798 unsigned key_size_index,
799 const blink::WebString& challenge,
800 const blink::WebURL& url) {
801 std::string signed_public_key;
802 RenderThread::Get()->Send(new ViewHostMsg_Keygen(
803 static_cast<uint32>(key_size_index),
804 challenge.utf8(),
805 GURL(url),
806 &signed_public_key));
807 return WebString::fromUTF8(signed_public_key);
810 //------------------------------------------------------------------------------
812 void RendererBlinkPlatformImpl::screenColorProfile(
813 WebVector<char>* to_profile) {
814 #if defined(OS_WIN)
815 // On Windows screen color profile is only available in the browser.
816 std::vector<char> profile;
817 // This Send() can be called from any impl-side thread. Use a thread
818 // safe send to avoid crashing trying to access RenderThread::Get(),
819 // which is not accessible from arbitrary threads.
820 thread_safe_sender_->Send(
821 new ViewHostMsg_GetMonitorColorProfile(&profile));
822 *to_profile = profile;
823 #else
824 // On other platforms, the primary monitor color profile can be read
825 // directly.
826 gfx::ColorProfile profile;
827 *to_profile = profile.profile();
828 #endif
831 //------------------------------------------------------------------------------
833 blink::WebScrollbarBehavior* RendererBlinkPlatformImpl::scrollbarBehavior() {
834 return web_scrollbar_behavior_.get();
837 //------------------------------------------------------------------------------
839 WebBlobRegistry* RendererBlinkPlatformImpl::blobRegistry() {
840 // blob_registry_ can be NULL when running some tests.
841 return blob_registry_.get();
844 //------------------------------------------------------------------------------
846 void RendererBlinkPlatformImpl::sampleGamepads(WebGamepads& gamepads) {
847 PlatformEventObserverBase* observer =
848 platform_event_observers_.Lookup(blink::WebPlatformEventGamepad);
849 if (!observer)
850 return;
851 static_cast<RendererGamepadProvider*>(observer)->SampleGamepads(gamepads);
854 //------------------------------------------------------------------------------
856 WebRTCPeerConnectionHandler*
857 RendererBlinkPlatformImpl::createRTCPeerConnectionHandler(
858 WebRTCPeerConnectionHandlerClient* client) {
859 RenderThreadImpl* render_thread = RenderThreadImpl::current();
860 DCHECK(render_thread);
861 if (!render_thread)
862 return NULL;
864 #if defined(ENABLE_WEBRTC)
865 WebRTCPeerConnectionHandler* peer_connection_handler =
866 GetContentClient()->renderer()->OverrideCreateWebRTCPeerConnectionHandler(
867 client);
868 if (peer_connection_handler)
869 return peer_connection_handler;
871 PeerConnectionDependencyFactory* rtc_dependency_factory =
872 render_thread->GetPeerConnectionDependencyFactory();
873 return rtc_dependency_factory->CreateRTCPeerConnectionHandler(client);
874 #else
875 return NULL;
876 #endif // defined(ENABLE_WEBRTC)
879 //------------------------------------------------------------------------------
881 WebMediaStreamCenter* RendererBlinkPlatformImpl::createMediaStreamCenter(
882 WebMediaStreamCenterClient* client) {
883 RenderThreadImpl* render_thread = RenderThreadImpl::current();
884 DCHECK(render_thread);
885 if (!render_thread)
886 return NULL;
887 return render_thread->CreateMediaStreamCenter(client);
890 // static
891 bool RendererBlinkPlatformImpl::SetSandboxEnabledForTesting(bool enable) {
892 bool was_enabled = g_sandbox_enabled;
893 g_sandbox_enabled = enable;
894 return was_enabled;
897 //------------------------------------------------------------------------------
899 blink::WebSpeechSynthesizer* RendererBlinkPlatformImpl::createSpeechSynthesizer(
900 blink::WebSpeechSynthesizerClient* client) {
901 return GetContentClient()->renderer()->OverrideSpeechSynthesizer(client);
904 //------------------------------------------------------------------------------
906 bool RendererBlinkPlatformImpl::processMemorySizesInBytes(
907 size_t* private_bytes,
908 size_t* shared_bytes) {
909 content::RenderThread::Get()->Send(
910 new ViewHostMsg_GetProcessMemorySizes(private_bytes, shared_bytes));
911 return true;
914 //------------------------------------------------------------------------------
916 blink::WebGraphicsContext3D*
917 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
918 const blink::WebGraphicsContext3D::Attributes& attributes) {
919 return createOffscreenGraphicsContext3D(attributes, NULL);
922 blink::WebGraphicsContext3D*
923 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
924 const blink::WebGraphicsContext3D::Attributes& attributes,
925 blink::WebGraphicsContext3D* share_context) {
926 return createOffscreenGraphicsContext3D(attributes, share_context, NULL);
929 blink::WebGraphicsContext3D*
930 RendererBlinkPlatformImpl::createOffscreenGraphicsContext3D(
931 const blink::WebGraphicsContext3D::Attributes& attributes,
932 blink::WebGraphicsContext3D* share_context,
933 blink::WebGLInfo* gl_info) {
934 if (!RenderThreadImpl::current())
935 return NULL;
937 #if defined(OS_ANDROID)
938 if (SynchronousCompositorFactory* factory =
939 SynchronousCompositorFactory::GetInstance()) {
940 scoped_ptr<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl>
941 in_process_context(
942 factory->CreateOffscreenGraphicsContext3D(attributes));
943 if (!in_process_context ||
944 !in_process_context->InitializeOnCurrentThread())
945 return NULL;
946 return in_process_context.release();
948 #endif
950 scoped_refptr<GpuChannelHost> gpu_channel_host(
951 RenderThreadImpl::current()->EstablishGpuChannelSync(
952 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
954 if (gpu_channel_host.get() && gl_info) {
955 const gpu::GPUInfo& gpu_info = gpu_channel_host->gpu_info();
956 switch (gpu_info.context_info_state) {
957 case gpu::kCollectInfoSuccess:
958 case gpu::kCollectInfoNonFatalFailure:
959 gl_info->vendorInfo.assign(
960 blink::WebString::fromUTF8(gpu_info.gl_vendor));
961 gl_info->rendererInfo.assign(
962 blink::WebString::fromUTF8(gpu_info.gl_renderer));
963 gl_info->driverVersion.assign(
964 blink::WebString::fromUTF8(gpu_info.driver_version));
965 gl_info->vendorId = gpu_info.gpu.vendor_id;
966 gl_info->deviceId = gpu_info.gpu.device_id;
967 break;
968 case gpu::kCollectInfoFatalFailure:
969 case gpu::kCollectInfoNone:
970 gl_info->contextInfoCollectionFailure.assign(blink::WebString::fromUTF8(
971 "GPUInfoCollectionFailure: GPU initialization Failed. GPU "
972 "Info not Collected."));
973 break;
974 default:
975 NOTREACHED();
979 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
980 bool lose_context_when_out_of_memory = false;
981 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
982 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
983 gpu_channel_host.get(),
984 attributes,
985 lose_context_when_out_of_memory,
986 GURL(attributes.topDocumentURL),
987 limits,
988 static_cast<WebGraphicsContext3DCommandBufferImpl*>(share_context)));
990 // Most likely the GPU process exited and the attempt to reconnect to it
991 // failed. Need to try to restore the context again later.
992 if (!context || !context->InitializeOnCurrentThread())
993 return NULL;
994 return context.release();
997 //------------------------------------------------------------------------------
999 blink::WebGraphicsContext3DProvider*
1000 RendererBlinkPlatformImpl::createSharedOffscreenGraphicsContext3DProvider() {
1001 scoped_refptr<cc_blink::ContextProviderWebContext> provider =
1002 RenderThreadImpl::current()->SharedMainThreadContextProvider();
1003 if (!provider.get())
1004 return NULL;
1005 return new WebGraphicsContext3DProviderImpl(provider);
1008 //------------------------------------------------------------------------------
1010 blink::WebCompositorSupport* RendererBlinkPlatformImpl::compositorSupport() {
1011 return &compositor_support_;
1014 //------------------------------------------------------------------------------
1016 blink::WebString RendererBlinkPlatformImpl::convertIDNToUnicode(
1017 const blink::WebString& host,
1018 const blink::WebString& languages) {
1019 return net::IDNToUnicode(host.utf8(), languages.utf8());
1022 //------------------------------------------------------------------------------
1024 // static
1025 void RendererBlinkPlatformImpl::SetMockDeviceLightDataForTesting(double data) {
1026 g_test_device_light_data = data;
1029 //------------------------------------------------------------------------------
1031 // static
1032 void RendererBlinkPlatformImpl::SetMockDeviceMotionDataForTesting(
1033 const blink::WebDeviceMotionData& data) {
1034 g_test_device_motion_data.Get() = data;
1037 //------------------------------------------------------------------------------
1039 // static
1040 void RendererBlinkPlatformImpl::SetMockDeviceOrientationDataForTesting(
1041 const blink::WebDeviceOrientationData& data) {
1042 g_test_device_orientation_data.Get() = data;
1045 //------------------------------------------------------------------------------
1047 void RendererBlinkPlatformImpl::vibrate(unsigned int milliseconds) {
1048 GetConnectedVibrationManagerService()->Vibrate(
1049 base::checked_cast<int64>(milliseconds));
1050 vibration_manager_.reset();
1053 void RendererBlinkPlatformImpl::cancelVibration() {
1054 GetConnectedVibrationManagerService()->Cancel();
1055 vibration_manager_.reset();
1058 device::VibrationManagerPtr&
1059 RendererBlinkPlatformImpl::GetConnectedVibrationManagerService() {
1060 if (!vibration_manager_) {
1061 RenderThread::Get()->GetServiceRegistry()
1062 ->ConnectToRemoteService(&vibration_manager_);
1064 return vibration_manager_;
1067 //------------------------------------------------------------------------------
1069 // static
1070 PlatformEventObserverBase*
1071 RendererBlinkPlatformImpl::CreatePlatformEventObserverFromType(
1072 blink::WebPlatformEventType type) {
1073 RenderThread* thread = RenderThreadImpl::current();
1075 // When running layout tests, those observers should not listen to the actual
1076 // hardware changes. In order to make that happen, they will receive a null
1077 // thread.
1078 if (thread && RenderThreadImpl::current()->layout_test_mode())
1079 thread = NULL;
1081 switch (type) {
1082 case blink::WebPlatformEventDeviceMotion:
1083 return new DeviceMotionEventPump(thread);
1084 case blink::WebPlatformEventDeviceOrientation:
1085 return new DeviceOrientationEventPump(thread);
1086 case blink::WebPlatformEventDeviceLight:
1087 return new DeviceLightEventPump(thread);
1088 case blink::WebPlatformEventGamepad:
1089 return new GamepadSharedMemoryReader(thread);
1090 case blink::WebPlatformEventScreenOrientation:
1091 return new ScreenOrientationObserver();
1092 default:
1093 // A default statement is required to prevent compilation errors when
1094 // Blink adds a new type.
1095 DVLOG(1) << "RendererBlinkPlatformImpl::startListening() with "
1096 "unknown type.";
1099 return NULL;
1102 void RendererBlinkPlatformImpl::SetPlatformEventObserverForTesting(
1103 blink::WebPlatformEventType type,
1104 scoped_ptr<PlatformEventObserverBase> observer) {
1105 DCHECK(type != blink::WebPlatformEventBattery);
1107 if (platform_event_observers_.Lookup(type))
1108 platform_event_observers_.Remove(type);
1109 platform_event_observers_.AddWithID(observer.release(), type);
1112 void RendererBlinkPlatformImpl::startListening(
1113 blink::WebPlatformEventType type,
1114 blink::WebPlatformEventListener* listener) {
1115 if (type == blink::WebPlatformEventBattery) {
1116 if (RenderThreadImpl::current() &&
1117 RenderThreadImpl::current()->layout_test_mode()) {
1118 g_test_battery_status_listener =
1119 static_cast<blink::WebBatteryStatusListener*>(listener);
1120 } else {
1121 battery_status_dispatcher_.reset(new BatteryStatusDispatcher(
1122 static_cast<blink::WebBatteryStatusListener*>(listener)));
1124 return;
1127 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1128 if (!observer) {
1129 observer = CreatePlatformEventObserverFromType(type);
1130 if (!observer)
1131 return;
1132 platform_event_observers_.AddWithID(observer, static_cast<int32>(type));
1134 observer->Start(listener);
1136 // Device events (motion, orientation and light) expect to get an event fired
1137 // as soon as a listener is registered if a fake data was passed before.
1138 // TODO(mlamouri,timvolodine): make those send mock values directly instead of
1139 // using this broken pattern.
1140 if (RenderThreadImpl::current() &&
1141 RenderThreadImpl::current()->layout_test_mode() &&
1142 (type == blink::WebPlatformEventDeviceMotion ||
1143 type == blink::WebPlatformEventDeviceOrientation ||
1144 type == blink::WebPlatformEventDeviceLight)) {
1145 SendFakeDeviceEventDataForTesting(type);
1149 void RendererBlinkPlatformImpl::SendFakeDeviceEventDataForTesting(
1150 blink::WebPlatformEventType type) {
1151 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1152 CHECK(observer);
1154 void* data = 0;
1156 switch (type) {
1157 case blink::WebPlatformEventDeviceMotion:
1158 if (!(g_test_device_motion_data == 0))
1159 data = &g_test_device_motion_data.Get();
1160 break;
1161 case blink::WebPlatformEventDeviceOrientation:
1162 if (!(g_test_device_orientation_data == 0))
1163 data = &g_test_device_orientation_data.Get();
1164 break;
1165 case blink::WebPlatformEventDeviceLight:
1166 if (g_test_device_light_data >= 0)
1167 data = &g_test_device_light_data;
1168 break;
1169 default:
1170 NOTREACHED();
1171 break;
1174 if (!data)
1175 return;
1177 base::MessageLoopProxy::current()->PostTask(
1178 FROM_HERE,
1179 base::Bind(&PlatformEventObserverBase::SendFakeDataForTesting,
1180 base::Unretained(observer), data));
1183 void RendererBlinkPlatformImpl::stopListening(
1184 blink::WebPlatformEventType type) {
1185 if (type == blink::WebPlatformEventBattery) {
1186 g_test_battery_status_listener = nullptr;
1187 battery_status_dispatcher_.reset();
1188 return;
1191 PlatformEventObserverBase* observer = platform_event_observers_.Lookup(type);
1192 if (!observer)
1193 return;
1194 observer->Stop();
1197 //------------------------------------------------------------------------------
1199 void RendererBlinkPlatformImpl::queryStorageUsageAndQuota(
1200 const blink::WebURL& storage_partition,
1201 blink::WebStorageQuotaType type,
1202 blink::WebStorageQuotaCallbacks callbacks) {
1203 if (!thread_safe_sender_.get() || !quota_message_filter_.get())
1204 return;
1205 QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(),
1206 quota_message_filter_.get())
1207 ->QueryStorageUsageAndQuota(
1208 storage_partition,
1209 static_cast<storage::StorageType>(type),
1210 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
1213 //------------------------------------------------------------------------------
1215 void RendererBlinkPlatformImpl::MockBatteryStatusChangedForTesting(
1216 const blink::WebBatteryStatus& status) {
1217 if (!g_test_battery_status_listener)
1218 return;
1219 g_test_battery_status_listener->updateBatteryStatus(status);
1222 } // namespace content