Roll src/third_party/WebKit 6cdd902:94953d6 (svn 197985:197991)
[chromium-blink-merge.git] / content / child / blink_platform_impl.cc
blob1bcceadb67f77c42ab953e92161df2494fe91154
1 // Copyright 2014 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/child/blink_platform_impl.h"
7 #include <math.h>
9 #include <vector>
11 #include "base/allocator/allocator_extension.h"
12 #include "base/bind.h"
13 #include "base/files/file_path.h"
14 #include "base/location.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/memory/singleton.h"
17 #include "base/metrics/histogram.h"
18 #include "base/metrics/sparse_histogram.h"
19 #include "base/process/process_metrics.h"
20 #include "base/rand_util.h"
21 #include "base/single_thread_task_runner.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/synchronization/lock.h"
26 #include "base/synchronization/waitable_event.h"
27 #include "base/sys_info.h"
28 #include "base/thread_task_runner_handle.h"
29 #include "base/threading/platform_thread.h"
30 #include "base/time/time.h"
31 #include "base/trace_event/memory_allocator_dump_guid.h"
32 #include "base/trace_event/memory_dump_manager.h"
33 #include "base/trace_event/trace_event.h"
34 #include "blink/public/resources/grit/blink_image_resources.h"
35 #include "blink/public/resources/grit/blink_resources.h"
36 #include "components/mime_util/mime_util.h"
37 #include "components/scheduler/child/webthread_impl_for_worker_scheduler.h"
38 #include "content/app/resources/grit/content_resources.h"
39 #include "content/app/strings/grit/content_strings.h"
40 #include "content/child/background_sync/background_sync_provider.h"
41 #include "content/child/background_sync/background_sync_provider_thread_proxy.h"
42 #include "content/child/bluetooth/web_bluetooth_impl.h"
43 #include "content/child/child_thread_impl.h"
44 #include "content/child/content_child_helpers.h"
45 #include "content/child/geofencing/web_geofencing_provider_impl.h"
46 #include "content/child/navigator_connect/navigator_connect_provider.h"
47 #include "content/child/notifications/notification_dispatcher.h"
48 #include "content/child/notifications/notification_manager.h"
49 #include "content/child/permissions/permission_dispatcher.h"
50 #include "content/child/permissions/permission_dispatcher_thread_proxy.h"
51 #include "content/child/push_messaging/push_dispatcher.h"
52 #include "content/child/push_messaging/push_provider.h"
53 #include "content/child/thread_safe_sender.h"
54 #include "content/child/web_discardable_memory_impl.h"
55 #include "content/child/web_memory_dump_provider_adapter.h"
56 #include "content/child/web_process_memory_dump_impl.h"
57 #include "content/child/web_url_loader_impl.h"
58 #include "content/child/web_url_request_util.h"
59 #include "content/child/websocket_bridge.h"
60 #include "content/child/worker_task_runner.h"
61 #include "content/public/common/content_client.h"
62 #include "net/base/data_url.h"
63 #include "net/base/ip_address_number.h"
64 #include "net/base/net_errors.h"
65 #include "net/base/net_util.h"
66 #include "third_party/WebKit/public/platform/WebConvertableToTraceFormat.h"
67 #include "third_party/WebKit/public/platform/WebData.h"
68 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
69 #include "third_party/WebKit/public/platform/WebMemoryDumpProvider.h"
70 #include "third_party/WebKit/public/platform/WebString.h"
71 #include "third_party/WebKit/public/platform/WebURL.h"
72 #include "third_party/WebKit/public/platform/WebWaitableEvent.h"
73 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
74 #include "ui/base/layout.h"
75 #include "ui/events/gestures/blink/web_gesture_curve_impl.h"
76 #include "ui/events/keycodes/dom/keycode_converter.h"
78 using blink::WebData;
79 using blink::WebFallbackThemeEngine;
80 using blink::WebLocalizedString;
81 using blink::WebString;
82 using blink::WebThemeEngine;
83 using blink::WebURL;
84 using blink::WebURLError;
85 using blink::WebURLLoader;
87 namespace content {
89 namespace {
91 class WebWaitableEventImpl : public blink::WebWaitableEvent {
92 public:
93 WebWaitableEventImpl() : impl_(new base::WaitableEvent(false, false)) {}
94 virtual ~WebWaitableEventImpl() {}
96 virtual void wait() { impl_->Wait(); }
97 virtual void signal() { impl_->Signal(); }
99 base::WaitableEvent* impl() {
100 return impl_.get();
103 private:
104 scoped_ptr<base::WaitableEvent> impl_;
105 DISALLOW_COPY_AND_ASSIGN(WebWaitableEventImpl);
108 // A simple class to cache the memory usage for a given amount of time.
109 class MemoryUsageCache {
110 public:
111 // Retrieves the Singleton.
112 static MemoryUsageCache* GetInstance() {
113 return Singleton<MemoryUsageCache>::get();
116 MemoryUsageCache() : memory_value_(0) { Init(); }
117 ~MemoryUsageCache() {}
119 void Init() {
120 const unsigned int kCacheSeconds = 1;
121 cache_valid_time_ = base::TimeDelta::FromSeconds(kCacheSeconds);
124 // Returns true if the cached value is fresh.
125 // Returns false if the cached value is stale, or if |cached_value| is NULL.
126 bool IsCachedValueValid(size_t* cached_value) {
127 base::AutoLock scoped_lock(lock_);
128 if (!cached_value)
129 return false;
130 if (base::Time::Now() - last_updated_time_ > cache_valid_time_)
131 return false;
132 *cached_value = memory_value_;
133 return true;
136 // Setter for |memory_value_|, refreshes |last_updated_time_|.
137 void SetMemoryValue(const size_t value) {
138 base::AutoLock scoped_lock(lock_);
139 memory_value_ = value;
140 last_updated_time_ = base::Time::Now();
143 private:
144 // The cached memory value.
145 size_t memory_value_;
147 // How long the cached value should remain valid.
148 base::TimeDelta cache_valid_time_;
150 // The last time the cached value was updated.
151 base::Time last_updated_time_;
153 base::Lock lock_;
156 class ConvertableToTraceFormatWrapper
157 : public base::trace_event::ConvertableToTraceFormat {
158 public:
159 // We move a reference pointer from |convertable| to |convertable_|,
160 // rather than copying, for thread safety. https://crbug.com/478149
161 explicit ConvertableToTraceFormatWrapper(
162 blink::WebConvertableToTraceFormat& convertable) {
163 convertable_.moveFrom(convertable);
165 void AppendAsTraceFormat(std::string* out) const override {
166 *out += convertable_.asTraceFormat().utf8();
169 private:
170 ~ConvertableToTraceFormatWrapper() override {}
172 blink::WebConvertableToTraceFormat convertable_;
175 } // namespace
177 static int ToMessageID(WebLocalizedString::Name name) {
178 switch (name) {
179 case WebLocalizedString::AXAMPMFieldText:
180 return IDS_AX_AM_PM_FIELD_TEXT;
181 case WebLocalizedString::AXButtonActionVerb:
182 return IDS_AX_BUTTON_ACTION_VERB;
183 case WebLocalizedString::AXCalendarShowMonthSelector:
184 return IDS_AX_CALENDAR_SHOW_MONTH_SELECTOR;
185 case WebLocalizedString::AXCalendarShowNextMonth:
186 return IDS_AX_CALENDAR_SHOW_NEXT_MONTH;
187 case WebLocalizedString::AXCalendarShowPreviousMonth:
188 return IDS_AX_CALENDAR_SHOW_PREVIOUS_MONTH;
189 case WebLocalizedString::AXCalendarWeekDescription:
190 return IDS_AX_CALENDAR_WEEK_DESCRIPTION;
191 case WebLocalizedString::AXCheckedCheckBoxActionVerb:
192 return IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB;
193 case WebLocalizedString::AXDateTimeFieldEmptyValueText:
194 return IDS_AX_DATE_TIME_FIELD_EMPTY_VALUE_TEXT;
195 case WebLocalizedString::AXDayOfMonthFieldText:
196 return IDS_AX_DAY_OF_MONTH_FIELD_TEXT;
197 case WebLocalizedString::AXHeadingText:
198 return IDS_AX_ROLE_HEADING;
199 case WebLocalizedString::AXHourFieldText:
200 return IDS_AX_HOUR_FIELD_TEXT;
201 case WebLocalizedString::AXImageMapText:
202 return IDS_AX_ROLE_IMAGE_MAP;
203 case WebLocalizedString::AXLinkActionVerb:
204 return IDS_AX_LINK_ACTION_VERB;
205 case WebLocalizedString::AXLinkText:
206 return IDS_AX_ROLE_LINK;
207 case WebLocalizedString::AXListMarkerText:
208 return IDS_AX_ROLE_LIST_MARKER;
209 case WebLocalizedString::AXMediaDefault:
210 return IDS_AX_MEDIA_DEFAULT;
211 case WebLocalizedString::AXMediaAudioElement:
212 return IDS_AX_MEDIA_AUDIO_ELEMENT;
213 case WebLocalizedString::AXMediaVideoElement:
214 return IDS_AX_MEDIA_VIDEO_ELEMENT;
215 case WebLocalizedString::AXMediaMuteButton:
216 return IDS_AX_MEDIA_MUTE_BUTTON;
217 case WebLocalizedString::AXMediaUnMuteButton:
218 return IDS_AX_MEDIA_UNMUTE_BUTTON;
219 case WebLocalizedString::AXMediaPlayButton:
220 return IDS_AX_MEDIA_PLAY_BUTTON;
221 case WebLocalizedString::AXMediaPauseButton:
222 return IDS_AX_MEDIA_PAUSE_BUTTON;
223 case WebLocalizedString::AXMediaSlider:
224 return IDS_AX_MEDIA_SLIDER;
225 case WebLocalizedString::AXMediaSliderThumb:
226 return IDS_AX_MEDIA_SLIDER_THUMB;
227 case WebLocalizedString::AXMediaCurrentTimeDisplay:
228 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY;
229 case WebLocalizedString::AXMediaTimeRemainingDisplay:
230 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY;
231 case WebLocalizedString::AXMediaStatusDisplay:
232 return IDS_AX_MEDIA_STATUS_DISPLAY;
233 case WebLocalizedString::AXMediaEnterFullscreenButton:
234 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON;
235 case WebLocalizedString::AXMediaExitFullscreenButton:
236 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON;
237 case WebLocalizedString::AXMediaShowClosedCaptionsButton:
238 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON;
239 case WebLocalizedString::AXMediaHideClosedCaptionsButton:
240 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON;
241 case WebLocalizedString::AxMediaCastOffButton:
242 return IDS_AX_MEDIA_CAST_OFF_BUTTON;
243 case WebLocalizedString::AxMediaCastOnButton:
244 return IDS_AX_MEDIA_CAST_ON_BUTTON;
245 case WebLocalizedString::AXMediaAudioElementHelp:
246 return IDS_AX_MEDIA_AUDIO_ELEMENT_HELP;
247 case WebLocalizedString::AXMediaVideoElementHelp:
248 return IDS_AX_MEDIA_VIDEO_ELEMENT_HELP;
249 case WebLocalizedString::AXMediaMuteButtonHelp:
250 return IDS_AX_MEDIA_MUTE_BUTTON_HELP;
251 case WebLocalizedString::AXMediaUnMuteButtonHelp:
252 return IDS_AX_MEDIA_UNMUTE_BUTTON_HELP;
253 case WebLocalizedString::AXMediaPlayButtonHelp:
254 return IDS_AX_MEDIA_PLAY_BUTTON_HELP;
255 case WebLocalizedString::AXMediaPauseButtonHelp:
256 return IDS_AX_MEDIA_PAUSE_BUTTON_HELP;
257 case WebLocalizedString::AXMediaAudioSliderHelp:
258 return IDS_AX_MEDIA_AUDIO_SLIDER_HELP;
259 case WebLocalizedString::AXMediaVideoSliderHelp:
260 return IDS_AX_MEDIA_VIDEO_SLIDER_HELP;
261 case WebLocalizedString::AXMediaSliderThumbHelp:
262 return IDS_AX_MEDIA_SLIDER_THUMB_HELP;
263 case WebLocalizedString::AXMediaCurrentTimeDisplayHelp:
264 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY_HELP;
265 case WebLocalizedString::AXMediaTimeRemainingDisplayHelp:
266 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY_HELP;
267 case WebLocalizedString::AXMediaStatusDisplayHelp:
268 return IDS_AX_MEDIA_STATUS_DISPLAY_HELP;
269 case WebLocalizedString::AXMediaEnterFullscreenButtonHelp:
270 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON_HELP;
271 case WebLocalizedString::AXMediaExitFullscreenButtonHelp:
272 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON_HELP;
273 case WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp:
274 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON_HELP;
275 case WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp:
276 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON_HELP;
277 case WebLocalizedString::AxMediaCastOffButtonHelp:
278 return IDS_AX_MEDIA_CAST_OFF_BUTTON_HELP;
279 case WebLocalizedString::AxMediaCastOnButtonHelp:
280 return IDS_AX_MEDIA_CAST_ON_BUTTON_HELP;
281 case WebLocalizedString::AXMillisecondFieldText:
282 return IDS_AX_MILLISECOND_FIELD_TEXT;
283 case WebLocalizedString::AXMinuteFieldText:
284 return IDS_AX_MINUTE_FIELD_TEXT;
285 case WebLocalizedString::AXMonthFieldText:
286 return IDS_AX_MONTH_FIELD_TEXT;
287 case WebLocalizedString::AXRadioButtonActionVerb:
288 return IDS_AX_RADIO_BUTTON_ACTION_VERB;
289 case WebLocalizedString::AXSecondFieldText:
290 return IDS_AX_SECOND_FIELD_TEXT;
291 case WebLocalizedString::AXTextFieldActionVerb:
292 return IDS_AX_TEXT_FIELD_ACTION_VERB;
293 case WebLocalizedString::AXUncheckedCheckBoxActionVerb:
294 return IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB;
295 case WebLocalizedString::AXWebAreaText:
296 return IDS_AX_ROLE_WEB_AREA;
297 case WebLocalizedString::AXWeekOfYearFieldText:
298 return IDS_AX_WEEK_OF_YEAR_FIELD_TEXT;
299 case WebLocalizedString::AXYearFieldText:
300 return IDS_AX_YEAR_FIELD_TEXT;
301 case WebLocalizedString::CalendarClear:
302 return IDS_FORM_CALENDAR_CLEAR;
303 case WebLocalizedString::CalendarToday:
304 return IDS_FORM_CALENDAR_TODAY;
305 case WebLocalizedString::DateFormatDayInMonthLabel:
306 return IDS_FORM_DATE_FORMAT_DAY_IN_MONTH;
307 case WebLocalizedString::DateFormatMonthLabel:
308 return IDS_FORM_DATE_FORMAT_MONTH;
309 case WebLocalizedString::DateFormatYearLabel:
310 return IDS_FORM_DATE_FORMAT_YEAR;
311 case WebLocalizedString::DetailsLabel:
312 return IDS_DETAILS_WITHOUT_SUMMARY_LABEL;
313 case WebLocalizedString::FileButtonChooseFileLabel:
314 return IDS_FORM_FILE_BUTTON_LABEL;
315 case WebLocalizedString::FileButtonChooseMultipleFilesLabel:
316 return IDS_FORM_MULTIPLE_FILES_BUTTON_LABEL;
317 case WebLocalizedString::FileButtonNoFileSelectedLabel:
318 return IDS_FORM_FILE_NO_FILE_LABEL;
319 case WebLocalizedString::InputElementAltText:
320 return IDS_FORM_INPUT_ALT;
321 case WebLocalizedString::KeygenMenuHighGradeKeySize:
322 return IDS_KEYGEN_HIGH_GRADE_KEY;
323 case WebLocalizedString::KeygenMenuMediumGradeKeySize:
324 return IDS_KEYGEN_MED_GRADE_KEY;
325 case WebLocalizedString::MissingPluginText:
326 return IDS_PLUGIN_INITIALIZATION_ERROR;
327 case WebLocalizedString::MultipleFileUploadText:
328 return IDS_FORM_FILE_MULTIPLE_UPLOAD;
329 case WebLocalizedString::OtherColorLabel:
330 return IDS_FORM_OTHER_COLOR_LABEL;
331 case WebLocalizedString::OtherDateLabel:
332 return IDS_FORM_OTHER_DATE_LABEL;
333 case WebLocalizedString::OtherMonthLabel:
334 return IDS_FORM_OTHER_MONTH_LABEL;
335 case WebLocalizedString::OtherTimeLabel:
336 return IDS_FORM_OTHER_TIME_LABEL;
337 case WebLocalizedString::OtherWeekLabel:
338 return IDS_FORM_OTHER_WEEK_LABEL;
339 case WebLocalizedString::PlaceholderForDayOfMonthField:
340 return IDS_FORM_PLACEHOLDER_FOR_DAY_OF_MONTH_FIELD;
341 case WebLocalizedString::PlaceholderForMonthField:
342 return IDS_FORM_PLACEHOLDER_FOR_MONTH_FIELD;
343 case WebLocalizedString::PlaceholderForYearField:
344 return IDS_FORM_PLACEHOLDER_FOR_YEAR_FIELD;
345 case WebLocalizedString::ResetButtonDefaultLabel:
346 return IDS_FORM_RESET_LABEL;
347 case WebLocalizedString::SearchableIndexIntroduction:
348 return IDS_SEARCHABLE_INDEX_INTRO;
349 case WebLocalizedString::SearchMenuClearRecentSearchesText:
350 return IDS_RECENT_SEARCHES_CLEAR;
351 case WebLocalizedString::SearchMenuNoRecentSearchesText:
352 return IDS_RECENT_SEARCHES_NONE;
353 case WebLocalizedString::SearchMenuRecentSearchesText:
354 return IDS_RECENT_SEARCHES;
355 case WebLocalizedString::SelectMenuListText:
356 return IDS_FORM_SELECT_MENU_LIST_TEXT;
357 case WebLocalizedString::SubmitButtonDefaultLabel:
358 return IDS_FORM_SUBMIT_LABEL;
359 case WebLocalizedString::ThisMonthButtonLabel:
360 return IDS_FORM_THIS_MONTH_LABEL;
361 case WebLocalizedString::ThisWeekButtonLabel:
362 return IDS_FORM_THIS_WEEK_LABEL;
363 case WebLocalizedString::ValidationBadInputForDateTime:
364 return IDS_FORM_VALIDATION_BAD_INPUT_DATETIME;
365 case WebLocalizedString::ValidationBadInputForNumber:
366 return IDS_FORM_VALIDATION_BAD_INPUT_NUMBER;
367 case WebLocalizedString::ValidationPatternMismatch:
368 return IDS_FORM_VALIDATION_PATTERN_MISMATCH;
369 case WebLocalizedString::ValidationRangeOverflow:
370 return IDS_FORM_VALIDATION_RANGE_OVERFLOW;
371 case WebLocalizedString::ValidationRangeOverflowDateTime:
372 return IDS_FORM_VALIDATION_RANGE_OVERFLOW_DATETIME;
373 case WebLocalizedString::ValidationRangeUnderflow:
374 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW;
375 case WebLocalizedString::ValidationRangeUnderflowDateTime:
376 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW_DATETIME;
377 case WebLocalizedString::ValidationStepMismatch:
378 return IDS_FORM_VALIDATION_STEP_MISMATCH;
379 case WebLocalizedString::ValidationStepMismatchCloseToLimit:
380 return IDS_FORM_VALIDATION_STEP_MISMATCH_CLOSE_TO_LIMIT;
381 case WebLocalizedString::ValidationTooLong:
382 return IDS_FORM_VALIDATION_TOO_LONG;
383 case WebLocalizedString::ValidationTooShort:
384 return IDS_FORM_VALIDATION_TOO_SHORT;
385 case WebLocalizedString::ValidationTypeMismatch:
386 return IDS_FORM_VALIDATION_TYPE_MISMATCH;
387 case WebLocalizedString::ValidationTypeMismatchForEmail:
388 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL;
389 case WebLocalizedString::ValidationTypeMismatchForEmailEmpty:
390 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY;
391 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyDomain:
392 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_DOMAIN;
393 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyLocal:
394 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_LOCAL;
395 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDomain:
396 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOMAIN;
397 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots:
398 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOTS;
399 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidLocal:
400 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_LOCAL;
401 case WebLocalizedString::ValidationTypeMismatchForEmailNoAtSign:
402 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_NO_AT_SIGN;
403 case WebLocalizedString::ValidationTypeMismatchForMultipleEmail:
404 return IDS_FORM_VALIDATION_TYPE_MISMATCH_MULTIPLE_EMAIL;
405 case WebLocalizedString::ValidationTypeMismatchForURL:
406 return IDS_FORM_VALIDATION_TYPE_MISMATCH_URL;
407 case WebLocalizedString::ValidationValueMissing:
408 return IDS_FORM_VALIDATION_VALUE_MISSING;
409 case WebLocalizedString::ValidationValueMissingForCheckbox:
410 return IDS_FORM_VALIDATION_VALUE_MISSING_CHECKBOX;
411 case WebLocalizedString::ValidationValueMissingForFile:
412 return IDS_FORM_VALIDATION_VALUE_MISSING_FILE;
413 case WebLocalizedString::ValidationValueMissingForMultipleFile:
414 return IDS_FORM_VALIDATION_VALUE_MISSING_MULTIPLE_FILE;
415 case WebLocalizedString::ValidationValueMissingForRadio:
416 return IDS_FORM_VALIDATION_VALUE_MISSING_RADIO;
417 case WebLocalizedString::ValidationValueMissingForSelect:
418 return IDS_FORM_VALIDATION_VALUE_MISSING_SELECT;
419 case WebLocalizedString::WeekFormatTemplate:
420 return IDS_FORM_INPUT_WEEK_TEMPLATE;
421 case WebLocalizedString::WeekNumberLabel:
422 return IDS_FORM_WEEK_NUMBER_LABEL;
423 // This "default:" line exists to avoid compile warnings about enum
424 // coverage when we add a new symbol to WebLocalizedString.h in WebKit.
425 // After a planned WebKit patch is landed, we need to add a case statement
426 // for the added symbol here.
427 default:
428 break;
430 return -1;
433 // TODO(skyostil): Ensure that we always have an active task runner when
434 // constructing the platform.
435 BlinkPlatformImpl::BlinkPlatformImpl()
436 : BlinkPlatformImpl(base::ThreadTaskRunnerHandle::IsSet()
437 ? base::ThreadTaskRunnerHandle::Get()
438 : nullptr) {
441 BlinkPlatformImpl::BlinkPlatformImpl(
442 scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner)
443 : main_thread_task_runner_(main_thread_task_runner) {
444 InternalInit();
447 void BlinkPlatformImpl::InternalInit() {
448 // ChildThread may not exist in some tests.
449 if (ChildThreadImpl::current()) {
450 geofencing_provider_.reset(new WebGeofencingProviderImpl(
451 ChildThreadImpl::current()->thread_safe_sender()));
452 bluetooth_.reset(
453 new WebBluetoothImpl(ChildThreadImpl::current()->thread_safe_sender()));
454 thread_safe_sender_ = ChildThreadImpl::current()->thread_safe_sender();
455 notification_dispatcher_ =
456 ChildThreadImpl::current()->notification_dispatcher();
457 push_dispatcher_ = ChildThreadImpl::current()->push_dispatcher();
458 permission_client_.reset(new PermissionDispatcher(
459 ChildThreadImpl::current()->service_registry()));
460 sync_provider_.reset(new BackgroundSyncProvider(
461 ChildThreadImpl::current()->service_registry()));
465 void BlinkPlatformImpl::UpdateWebThreadTLS(blink::WebThread* thread) {
466 DCHECK(!current_thread_slot_.Get());
467 current_thread_slot_.Set(thread);
470 BlinkPlatformImpl::~BlinkPlatformImpl() {
473 WebURLLoader* BlinkPlatformImpl::createURLLoader() {
474 ChildThreadImpl* child_thread = ChildThreadImpl::current();
475 // There may be no child thread in RenderViewTests. These tests can still use
476 // data URLs to bypass the ResourceDispatcher.
477 return new WebURLLoaderImpl(
478 child_thread ? child_thread->resource_dispatcher() : NULL,
479 MainTaskRunnerForCurrentThread());
482 blink::WebSocketHandle* BlinkPlatformImpl::createWebSocketHandle() {
483 return new WebSocketBridge;
486 WebString BlinkPlatformImpl::userAgent() {
487 return WebString::fromUTF8(GetContentClient()->GetUserAgent());
490 WebData BlinkPlatformImpl::parseDataURL(const WebURL& url,
491 WebString& mimetype_out,
492 WebString& charset_out) {
493 std::string mime_type, char_set, data;
494 if (net::DataURL::Parse(url, &mime_type, &char_set, &data) &&
495 mime_util::IsSupportedMimeType(mime_type)) {
496 mimetype_out = WebString::fromUTF8(mime_type);
497 charset_out = WebString::fromUTF8(char_set);
498 return data;
500 return WebData();
503 WebURLError BlinkPlatformImpl::cancelledError(
504 const WebURL& unreachableURL) const {
505 return CreateWebURLError(unreachableURL, false, net::ERR_ABORTED);
508 bool BlinkPlatformImpl::isReservedIPAddress(
509 const blink::WebString& host) const {
510 net::IPAddressNumber address;
511 if (!net::ParseURLHostnameToNumber(host.utf8(), &address))
512 return false;
513 return net::IsIPAddressReserved(address);
516 bool BlinkPlatformImpl::portAllowed(const blink::WebURL& url) const {
517 GURL gurl = GURL(url);
518 // Return true for URLs without a port specified. This is needed to let
519 // through non-network schemes that don't go over the network.
520 if (!gurl.has_port())
521 return true;
522 return net::IsPortAllowedForScheme(gurl.EffectiveIntPort(), gurl.scheme());
525 blink::WebThread* BlinkPlatformImpl::createThread(const char* name) {
526 scheduler::WebThreadImplForWorkerScheduler* thread =
527 new scheduler::WebThreadImplForWorkerScheduler(name);
528 thread->TaskRunner()->PostTask(
529 FROM_HERE, base::Bind(&BlinkPlatformImpl::UpdateWebThreadTLS,
530 base::Unretained(this), thread));
531 return thread;
534 blink::WebThread* BlinkPlatformImpl::currentThread() {
535 return static_cast<blink::WebThread*>(current_thread_slot_.Get());
538 void BlinkPlatformImpl::yieldCurrentThread() {
539 base::PlatformThread::YieldCurrentThread();
542 blink::WebWaitableEvent* BlinkPlatformImpl::createWaitableEvent() {
543 return new WebWaitableEventImpl();
546 blink::WebWaitableEvent* BlinkPlatformImpl::waitMultipleEvents(
547 const blink::WebVector<blink::WebWaitableEvent*>& web_events) {
548 std::vector<base::WaitableEvent*> events;
549 for (size_t i = 0; i < web_events.size(); ++i)
550 events.push_back(static_cast<WebWaitableEventImpl*>(web_events[i])->impl());
551 size_t idx = base::WaitableEvent::WaitMany(
552 vector_as_array(&events), events.size());
553 DCHECK_LT(idx, web_events.size());
554 return web_events[idx];
557 void BlinkPlatformImpl::decrementStatsCounter(const char* name) {
560 void BlinkPlatformImpl::incrementStatsCounter(const char* name) {
563 void BlinkPlatformImpl::histogramCustomCounts(
564 const char* name, int sample, int min, int max, int bucket_count) {
565 // Copied from histogram macro, but without the static variable caching
566 // the histogram because name is dynamic.
567 base::HistogramBase* counter =
568 base::Histogram::FactoryGet(name, min, max, bucket_count,
569 base::HistogramBase::kUmaTargetedHistogramFlag);
570 DCHECK_EQ(name, counter->histogram_name());
571 counter->Add(sample);
574 void BlinkPlatformImpl::histogramEnumeration(
575 const char* name, int sample, int boundary_value) {
576 // Copied from histogram macro, but without the static variable caching
577 // the histogram because name is dynamic.
578 base::HistogramBase* counter =
579 base::LinearHistogram::FactoryGet(name, 1, boundary_value,
580 boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
581 DCHECK_EQ(name, counter->histogram_name());
582 counter->Add(sample);
585 void BlinkPlatformImpl::histogramSparse(const char* name, int sample) {
586 // For sparse histograms, we can use the macro, as it does not incorporate a
587 // static.
588 UMA_HISTOGRAM_SPARSE_SLOWLY(name, sample);
591 const unsigned char* BlinkPlatformImpl::getTraceCategoryEnabledFlag(
592 const char* category_group) {
593 return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(category_group);
596 blink::Platform::TraceEventAPIAtomicWord*
597 BlinkPlatformImpl::getTraceSamplingState(const unsigned thread_bucket) {
598 switch (thread_bucket) {
599 case 0:
600 return reinterpret_cast<blink::Platform::TraceEventAPIAtomicWord*>(
601 &TRACE_EVENT_API_THREAD_BUCKET(0));
602 case 1:
603 return reinterpret_cast<blink::Platform::TraceEventAPIAtomicWord*>(
604 &TRACE_EVENT_API_THREAD_BUCKET(1));
605 case 2:
606 return reinterpret_cast<blink::Platform::TraceEventAPIAtomicWord*>(
607 &TRACE_EVENT_API_THREAD_BUCKET(2));
608 default:
609 NOTREACHED() << "Unknown thread bucket type.";
611 return NULL;
614 static_assert(
615 sizeof(blink::Platform::TraceEventHandle) ==
616 sizeof(base::trace_event::TraceEventHandle),
617 "TraceEventHandle types must be same size");
619 blink::Platform::TraceEventHandle BlinkPlatformImpl::addTraceEvent(
620 char phase,
621 const unsigned char* category_group_enabled,
622 const char* name,
623 unsigned long long id,
624 double timestamp,
625 int num_args,
626 const char** arg_names,
627 const unsigned char* arg_types,
628 const unsigned long long* arg_values,
629 unsigned char flags) {
630 base::TraceTicks timestamp_tt =
631 base::TraceTicks() + base::TimeDelta::FromSecondsD(timestamp);
632 base::trace_event::TraceEventHandle handle =
633 TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_THREAD_ID_AND_TIMESTAMP(
634 phase, category_group_enabled, name, id,
635 base::PlatformThread::CurrentId(),
636 timestamp_tt,
637 num_args, arg_names, arg_types, arg_values, NULL, flags);
638 blink::Platform::TraceEventHandle result;
639 memcpy(&result, &handle, sizeof(result));
640 return result;
643 blink::Platform::TraceEventHandle BlinkPlatformImpl::addTraceEvent(
644 char phase,
645 const unsigned char* category_group_enabled,
646 const char* name,
647 unsigned long long id,
648 double timestamp,
649 int num_args,
650 const char** arg_names,
651 const unsigned char* arg_types,
652 const unsigned long long* arg_values,
653 blink::WebConvertableToTraceFormat* convertable_values,
654 unsigned char flags) {
655 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
656 convertable_wrappers[2];
657 if (convertable_values) {
658 size_t size = std::min(static_cast<size_t>(num_args),
659 arraysize(convertable_wrappers));
660 for (size_t i = 0; i < size; ++i) {
661 if (arg_types[i] == TRACE_VALUE_TYPE_CONVERTABLE) {
662 convertable_wrappers[i] =
663 new ConvertableToTraceFormatWrapper(convertable_values[i]);
667 base::TraceTicks timestamp_tt =
668 base::TraceTicks() + base::TimeDelta::FromSecondsD(timestamp);
669 base::trace_event::TraceEventHandle handle =
670 TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_THREAD_ID_AND_TIMESTAMP(phase,
671 category_group_enabled,
672 name,
674 base::PlatformThread::CurrentId(),
675 timestamp_tt,
676 num_args,
677 arg_names,
678 arg_types,
679 arg_values,
680 convertable_wrappers,
681 flags);
682 blink::Platform::TraceEventHandle result;
683 memcpy(&result, &handle, sizeof(result));
684 return result;
687 void BlinkPlatformImpl::updateTraceEventDuration(
688 const unsigned char* category_group_enabled,
689 const char* name,
690 TraceEventHandle handle) {
691 base::trace_event::TraceEventHandle traceEventHandle;
692 memcpy(&traceEventHandle, &handle, sizeof(handle));
693 TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(
694 category_group_enabled, name, traceEventHandle);
697 void BlinkPlatformImpl::registerMemoryDumpProvider(
698 blink::WebMemoryDumpProvider* wmdp) {
699 WebMemoryDumpProviderAdapter* wmdp_adapter =
700 new WebMemoryDumpProviderAdapter(wmdp);
701 bool did_insert =
702 memory_dump_providers_.add(wmdp, make_scoped_ptr(wmdp_adapter)).second;
703 if (!did_insert)
704 return;
705 wmdp_adapter->set_is_registered(true);
706 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
707 wmdp_adapter, base::ThreadTaskRunnerHandle::Get());
710 void BlinkPlatformImpl::unregisterMemoryDumpProvider(
711 blink::WebMemoryDumpProvider* wmdp) {
712 scoped_ptr<WebMemoryDumpProviderAdapter> wmdp_adapter =
713 memory_dump_providers_.take_and_erase(wmdp);
714 if (!wmdp_adapter)
715 return;
716 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
717 wmdp_adapter.get());
718 wmdp_adapter->set_is_registered(false);
721 blink::WebProcessMemoryDump* BlinkPlatformImpl::createProcessMemoryDump() {
722 return new WebProcessMemoryDumpImpl();
725 blink::Platform::WebMemoryAllocatorDumpGuid
726 BlinkPlatformImpl::createWebMemoryAllocatorDumpGuid(
727 const blink::WebString& guidStr) {
728 return base::trace_event::MemoryAllocatorDumpGuid(guidStr.utf8()).ToUint64();
731 namespace {
733 WebData loadAudioSpatializationResource(const char* name) {
734 #ifdef IDR_AUDIO_SPATIALIZATION_COMPOSITE
735 if (!strcmp(name, "Composite")) {
736 base::StringPiece resource = GetContentClient()->GetDataResource(
737 IDR_AUDIO_SPATIALIZATION_COMPOSITE, ui::SCALE_FACTOR_NONE);
738 return WebData(resource.data(), resource.size());
740 #endif
742 #ifdef IDR_AUDIO_SPATIALIZATION_T000_P000
743 const size_t kExpectedSpatializationNameLength = 31;
744 if (strlen(name) != kExpectedSpatializationNameLength) {
745 return WebData();
748 // Extract the azimuth and elevation from the resource name.
749 int azimuth = 0;
750 int elevation = 0;
751 int values_parsed =
752 sscanf(name, "IRC_Composite_C_R0195_T%3d_P%3d", &azimuth, &elevation);
753 if (values_parsed != 2) {
754 return WebData();
757 // The resource index values go through the elevations first, then azimuths.
758 const int kAngleSpacing = 15;
760 // 0 <= elevation <= 90 (or 315 <= elevation <= 345)
761 // in increments of 15 degrees.
762 int elevation_index =
763 elevation <= 90 ? elevation / kAngleSpacing :
764 7 + (elevation - 315) / kAngleSpacing;
765 bool is_elevation_index_good = 0 <= elevation_index && elevation_index < 10;
767 // 0 <= azimuth < 360 in increments of 15 degrees.
768 int azimuth_index = azimuth / kAngleSpacing;
769 bool is_azimuth_index_good = 0 <= azimuth_index && azimuth_index < 24;
771 const int kNumberOfElevations = 10;
772 const int kNumberOfAudioResources = 240;
773 int resource_index = kNumberOfElevations * azimuth_index + elevation_index;
774 bool is_resource_index_good = 0 <= resource_index &&
775 resource_index < kNumberOfAudioResources;
777 if (is_azimuth_index_good && is_elevation_index_good &&
778 is_resource_index_good) {
779 const int kFirstAudioResourceIndex = IDR_AUDIO_SPATIALIZATION_T000_P000;
780 base::StringPiece resource = GetContentClient()->GetDataResource(
781 kFirstAudioResourceIndex + resource_index, ui::SCALE_FACTOR_NONE);
782 return WebData(resource.data(), resource.size());
784 #endif // IDR_AUDIO_SPATIALIZATION_T000_P000
786 NOTREACHED();
787 return WebData();
790 struct DataResource {
791 const char* name;
792 int id;
793 ui::ScaleFactor scale_factor;
796 const DataResource kDataResources[] = {
797 {"missingImage", IDR_BROKENIMAGE, ui::SCALE_FACTOR_100P},
798 {"missingImage@2x", IDR_BROKENIMAGE, ui::SCALE_FACTOR_200P},
799 {"mediaplayerPause", IDR_MEDIAPLAYER_PAUSE_BUTTON, ui::SCALE_FACTOR_100P},
800 {"mediaplayerPauseNew",
801 IDR_MEDIAPLAYER_PAUSE_BUTTON_NEW,
802 ui::SCALE_FACTOR_100P},
803 {"mediaplayerPauseHover",
804 IDR_MEDIAPLAYER_PAUSE_BUTTON_HOVER,
805 ui::SCALE_FACTOR_100P},
806 {"mediaplayerPauseDown",
807 IDR_MEDIAPLAYER_PAUSE_BUTTON_DOWN,
808 ui::SCALE_FACTOR_100P},
809 {"mediaplayerPlay", IDR_MEDIAPLAYER_PLAY_BUTTON, ui::SCALE_FACTOR_100P},
810 {"mediaplayerPlayNew",
811 IDR_MEDIAPLAYER_PLAY_BUTTON_NEW,
812 ui::SCALE_FACTOR_100P},
813 {"mediaplayerPlayHover",
814 IDR_MEDIAPLAYER_PLAY_BUTTON_HOVER,
815 ui::SCALE_FACTOR_100P},
816 {"mediaplayerPlayDown",
817 IDR_MEDIAPLAYER_PLAY_BUTTON_DOWN,
818 ui::SCALE_FACTOR_100P},
819 {"mediaplayerPlayDisabled",
820 IDR_MEDIAPLAYER_PLAY_BUTTON_DISABLED,
821 ui::SCALE_FACTOR_100P},
822 {"mediaplayerSoundLevel3",
823 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON,
824 ui::SCALE_FACTOR_100P},
825 {"mediaplayerSoundLevel3New",
826 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_NEW,
827 ui::SCALE_FACTOR_100P},
828 {"mediaplayerSoundLevel3Hover",
829 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_HOVER,
830 ui::SCALE_FACTOR_100P},
831 {"mediaplayerSoundLevel3Down",
832 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_DOWN,
833 ui::SCALE_FACTOR_100P},
834 {"mediaplayerSoundLevel2",
835 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON,
836 ui::SCALE_FACTOR_100P},
837 {"mediaplayerSoundLevel2Hover",
838 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_HOVER,
839 ui::SCALE_FACTOR_100P},
840 {"mediaplayerSoundLevel2Down",
841 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_DOWN,
842 ui::SCALE_FACTOR_100P},
843 {"mediaplayerSoundLevel1",
844 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON,
845 ui::SCALE_FACTOR_100P},
846 {"mediaplayerSoundLevel1Hover",
847 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_HOVER,
848 ui::SCALE_FACTOR_100P},
849 {"mediaplayerSoundLevel1Down",
850 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_DOWN,
851 ui::SCALE_FACTOR_100P},
852 {"mediaplayerSoundLevel0",
853 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON,
854 ui::SCALE_FACTOR_100P},
855 {"mediaplayerSoundLevel0New",
856 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_NEW,
857 ui::SCALE_FACTOR_100P},
858 {"mediaplayerSoundLevel0Hover",
859 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_HOVER,
860 ui::SCALE_FACTOR_100P},
861 {"mediaplayerSoundLevel0Down",
862 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_DOWN,
863 ui::SCALE_FACTOR_100P},
864 {"mediaplayerSoundDisabled",
865 IDR_MEDIAPLAYER_SOUND_DISABLED,
866 ui::SCALE_FACTOR_100P},
867 {"mediaplayerSliderThumb",
868 IDR_MEDIAPLAYER_SLIDER_THUMB,
869 ui::SCALE_FACTOR_100P},
870 {"mediaplayerSliderThumbNew",
871 IDR_MEDIAPLAYER_SLIDER_THUMB_NEW,
872 ui::SCALE_FACTOR_100P},
873 {"mediaplayerSliderThumbHover",
874 IDR_MEDIAPLAYER_SLIDER_THUMB_HOVER,
875 ui::SCALE_FACTOR_100P},
876 {"mediaplayerSliderThumbDown",
877 IDR_MEDIAPLAYER_SLIDER_THUMB_DOWN,
878 ui::SCALE_FACTOR_100P},
879 {"mediaplayerVolumeSliderThumb",
880 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB,
881 ui::SCALE_FACTOR_100P},
882 {"mediaplayerVolumeSliderThumbNew",
883 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_NEW,
884 ui::SCALE_FACTOR_100P},
885 {"mediaplayerVolumeSliderThumbHover",
886 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_HOVER,
887 ui::SCALE_FACTOR_100P},
888 {"mediaplayerVolumeSliderThumbDown",
889 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DOWN,
890 ui::SCALE_FACTOR_100P},
891 {"mediaplayerVolumeSliderThumbDisabled",
892 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DISABLED,
893 ui::SCALE_FACTOR_100P},
894 {"mediaplayerClosedCaption",
895 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON,
896 ui::SCALE_FACTOR_100P},
897 {"mediaplayerClosedCaptionNew",
898 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_NEW,
899 ui::SCALE_FACTOR_100P},
900 {"mediaplayerClosedCaptionHover",
901 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_HOVER,
902 ui::SCALE_FACTOR_100P},
903 {"mediaplayerClosedCaptionDown",
904 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DOWN,
905 ui::SCALE_FACTOR_100P},
906 {"mediaplayerClosedCaptionDisabled",
907 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DISABLED,
908 ui::SCALE_FACTOR_100P},
909 {"mediaplayerClosedCaptionDisabledNew",
910 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DISABLED_NEW,
911 ui::SCALE_FACTOR_100P},
912 {"mediaplayerEnterFullscreen",
913 IDR_MEDIAPLAYER_ENTER_FULLSCREEN_BUTTON,
914 ui::SCALE_FACTOR_100P},
915 {"mediaplayerExitFullscreen",
916 IDR_MEDIAPLAYER_EXIT_FULLSCREEN_BUTTON,
917 ui::SCALE_FACTOR_100P},
918 {"mediaplayerFullscreen",
919 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON,
920 ui::SCALE_FACTOR_100P},
921 {"mediaplayerFullscreenHover",
922 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_HOVER,
923 ui::SCALE_FACTOR_100P},
924 {"mediaplayerFullscreenDown",
925 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DOWN,
926 ui::SCALE_FACTOR_100P},
927 {"mediaplayerCastOff",
928 IDR_MEDIAPLAYER_CAST_BUTTON_OFF,
929 ui::SCALE_FACTOR_100P},
930 {"mediaplayerCastOn",
931 IDR_MEDIAPLAYER_CAST_BUTTON_ON,
932 ui::SCALE_FACTOR_100P},
933 {"mediaplayerCastOffNew",
934 IDR_MEDIAPLAYER_CAST_BUTTON_OFF_NEW,
935 ui::SCALE_FACTOR_100P},
936 {"mediaplayerCastOnNew",
937 IDR_MEDIAPLAYER_CAST_BUTTON_ON_NEW,
938 ui::SCALE_FACTOR_100P},
939 {"mediaplayerFullscreenDisabled",
940 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DISABLED,
941 ui::SCALE_FACTOR_100P},
942 {"mediaplayerOverlayCastOff",
943 IDR_MEDIAPLAYER_OVERLAY_CAST_BUTTON_OFF,
944 ui::SCALE_FACTOR_100P},
945 {"mediaplayerOverlayCastOffNew",
946 IDR_MEDIAPLAYER_OVERLAY_CAST_BUTTON_OFF_NEW,
947 ui::SCALE_FACTOR_100P},
948 {"mediaplayerOverlayPlay",
949 IDR_MEDIAPLAYER_OVERLAY_PLAY_BUTTON,
950 ui::SCALE_FACTOR_100P},
951 {"mediaplayerOverlayPlayNew",
952 IDR_MEDIAPLAYER_OVERLAY_PLAY_BUTTON_NEW,
953 ui::SCALE_FACTOR_100P},
954 {"panIcon", IDR_PAN_SCROLL_ICON, ui::SCALE_FACTOR_100P},
955 {"searchCancel", IDR_SEARCH_CANCEL, ui::SCALE_FACTOR_100P},
956 {"searchCancelPressed", IDR_SEARCH_CANCEL_PRESSED, ui::SCALE_FACTOR_100P},
957 {"searchMagnifier", IDR_SEARCH_MAGNIFIER, ui::SCALE_FACTOR_100P},
958 {"searchMagnifierResults",
959 IDR_SEARCH_MAGNIFIER_RESULTS,
960 ui::SCALE_FACTOR_100P},
961 {"textAreaResizeCorner", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_100P},
962 {"textAreaResizeCorner@2x", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_200P},
963 {"generatePassword", IDR_PASSWORD_GENERATION_ICON, ui::SCALE_FACTOR_100P},
964 {"generatePasswordHover",
965 IDR_PASSWORD_GENERATION_ICON_HOVER,
966 ui::SCALE_FACTOR_100P},
967 {"html.css", IDR_UASTYLE_HTML_CSS, ui::SCALE_FACTOR_NONE},
968 {"quirks.css", IDR_UASTYLE_QUIRKS_CSS, ui::SCALE_FACTOR_NONE},
969 {"view-source.css", IDR_UASTYLE_VIEW_SOURCE_CSS, ui::SCALE_FACTOR_NONE},
970 {"themeChromium.css",
971 IDR_UASTYLE_THEME_CHROMIUM_CSS,
972 ui::SCALE_FACTOR_NONE},
973 #if defined(OS_ANDROID)
974 {"themeChromiumAndroid.css",
975 IDR_UASTYLE_THEME_CHROMIUM_ANDROID_CSS,
976 ui::SCALE_FACTOR_NONE},
977 {"mediaControlsAndroid.css",
978 IDR_UASTYLE_MEDIA_CONTROLS_ANDROID_CSS,
979 ui::SCALE_FACTOR_NONE},
980 {"mediaControlsAndroidNew.css",
981 IDR_UASTYLE_MEDIA_CONTROLS_ANDROID_NEW_CSS,
982 ui::SCALE_FACTOR_NONE},
983 #endif
984 #if !defined(OS_WIN)
985 {"themeChromiumLinux.css",
986 IDR_UASTYLE_THEME_CHROMIUM_LINUX_CSS,
987 ui::SCALE_FACTOR_NONE},
988 #endif
989 {"themeChromiumSkia.css",
990 IDR_UASTYLE_THEME_CHROMIUM_SKIA_CSS,
991 ui::SCALE_FACTOR_NONE},
992 {"themeInputMultipleFields.css",
993 IDR_UASTYLE_THEME_INPUT_MULTIPLE_FIELDS_CSS,
994 ui::SCALE_FACTOR_NONE},
995 #if defined(OS_MACOSX)
996 {"themeMac.css", IDR_UASTYLE_THEME_MAC_CSS, ui::SCALE_FACTOR_NONE},
997 #endif
998 {"themeWin.css", IDR_UASTYLE_THEME_WIN_CSS, ui::SCALE_FACTOR_NONE},
999 {"themeWinQuirks.css",
1000 IDR_UASTYLE_THEME_WIN_QUIRKS_CSS,
1001 ui::SCALE_FACTOR_NONE},
1002 {"svg.css", IDR_UASTYLE_SVG_CSS, ui::SCALE_FACTOR_NONE},
1003 {"mathml.css", IDR_UASTYLE_MATHML_CSS, ui::SCALE_FACTOR_NONE},
1004 {"mediaControls.css",
1005 IDR_UASTYLE_MEDIA_CONTROLS_CSS,
1006 ui::SCALE_FACTOR_NONE},
1007 {"mediaControlsNew.css",
1008 IDR_UASTYLE_MEDIA_CONTROLS_NEW_CSS,
1009 ui::SCALE_FACTOR_NONE},
1010 {"fullscreen.css", IDR_UASTYLE_FULLSCREEN_CSS, ui::SCALE_FACTOR_NONE},
1011 {"xhtmlmp.css", IDR_UASTYLE_XHTMLMP_CSS, ui::SCALE_FACTOR_NONE},
1012 {"viewportAndroid.css",
1013 IDR_UASTYLE_VIEWPORT_ANDROID_CSS,
1014 ui::SCALE_FACTOR_NONE},
1015 {"InspectorOverlayPage.html",
1016 IDR_INSPECTOR_OVERLAY_PAGE_HTML,
1017 ui::SCALE_FACTOR_NONE},
1018 {"InjectedScriptSource.js",
1019 IDR_INSPECTOR_INJECTED_SCRIPT_SOURCE_JS,
1020 ui::SCALE_FACTOR_NONE},
1021 {"DebuggerScriptSource.js",
1022 IDR_INSPECTOR_DEBUGGER_SCRIPT_SOURCE_JS,
1023 ui::SCALE_FACTOR_NONE},
1024 {"DocumentExecCommand.js",
1025 IDR_PRIVATE_SCRIPT_DOCUMENTEXECCOMMAND_JS,
1026 ui::SCALE_FACTOR_NONE},
1027 {"DocumentXMLTreeViewer.css",
1028 IDR_PRIVATE_SCRIPT_DOCUMENTXMLTREEVIEWER_CSS,
1029 ui::SCALE_FACTOR_NONE},
1030 {"DocumentXMLTreeViewer.js",
1031 IDR_PRIVATE_SCRIPT_DOCUMENTXMLTREEVIEWER_JS,
1032 ui::SCALE_FACTOR_NONE},
1033 {"HTMLMarqueeElement.js",
1034 IDR_PRIVATE_SCRIPT_HTMLMARQUEEELEMENT_JS,
1035 ui::SCALE_FACTOR_NONE},
1036 {"PluginPlaceholderElement.js",
1037 IDR_PRIVATE_SCRIPT_PLUGINPLACEHOLDERELEMENT_JS,
1038 ui::SCALE_FACTOR_NONE},
1039 {"PrivateScriptRunner.js",
1040 IDR_PRIVATE_SCRIPT_PRIVATESCRIPTRUNNER_JS,
1041 ui::SCALE_FACTOR_NONE},
1042 #ifdef IDR_PICKER_COMMON_JS
1043 {"pickerCommon.js", IDR_PICKER_COMMON_JS, ui::SCALE_FACTOR_NONE},
1044 {"pickerCommon.css", IDR_PICKER_COMMON_CSS, ui::SCALE_FACTOR_NONE},
1045 {"calendarPicker.js", IDR_CALENDAR_PICKER_JS, ui::SCALE_FACTOR_NONE},
1046 {"calendarPicker.css", IDR_CALENDAR_PICKER_CSS, ui::SCALE_FACTOR_NONE},
1047 {"listPicker.js", IDR_LIST_PICKER_JS, ui::SCALE_FACTOR_NONE},
1048 {"listPicker.css", IDR_LIST_PICKER_CSS, ui::SCALE_FACTOR_NONE},
1049 {"pickerButton.css", IDR_PICKER_BUTTON_CSS, ui::SCALE_FACTOR_NONE},
1050 {"suggestionPicker.js", IDR_SUGGESTION_PICKER_JS, ui::SCALE_FACTOR_NONE},
1051 {"suggestionPicker.css", IDR_SUGGESTION_PICKER_CSS, ui::SCALE_FACTOR_NONE},
1052 {"colorSuggestionPicker.js",
1053 IDR_COLOR_SUGGESTION_PICKER_JS,
1054 ui::SCALE_FACTOR_NONE},
1055 {"colorSuggestionPicker.css",
1056 IDR_COLOR_SUGGESTION_PICKER_CSS,
1057 ui::SCALE_FACTOR_NONE},
1058 #endif
1061 } // namespace
1063 WebData BlinkPlatformImpl::loadResource(const char* name) {
1064 // Some clients will call into this method with an empty |name| when they have
1065 // optional resources. For example, the PopupMenuChromium code can have icons
1066 // for some Autofill items but not for others.
1067 if (!strlen(name))
1068 return WebData();
1070 // Check the name prefix to see if it's an audio resource.
1071 if (base::StartsWithASCII(name, "IRC_Composite", true) ||
1072 base::StartsWithASCII(name, "Composite", true))
1073 return loadAudioSpatializationResource(name);
1075 // TODO(flackr): We should use a better than linear search here, a trie would
1076 // be ideal.
1077 for (size_t i = 0; i < arraysize(kDataResources); ++i) {
1078 if (!strcmp(name, kDataResources[i].name)) {
1079 base::StringPiece resource = GetContentClient()->GetDataResource(
1080 kDataResources[i].id, kDataResources[i].scale_factor);
1081 return WebData(resource.data(), resource.size());
1085 NOTREACHED() << "Unknown image resource " << name;
1086 return WebData();
1089 WebString BlinkPlatformImpl::queryLocalizedString(
1090 WebLocalizedString::Name name) {
1091 int message_id = ToMessageID(name);
1092 if (message_id < 0)
1093 return WebString();
1094 return GetContentClient()->GetLocalizedString(message_id);
1097 WebString BlinkPlatformImpl::queryLocalizedString(
1098 WebLocalizedString::Name name, int numeric_value) {
1099 return queryLocalizedString(name, base::IntToString16(numeric_value));
1102 WebString BlinkPlatformImpl::queryLocalizedString(
1103 WebLocalizedString::Name name, const WebString& value) {
1104 int message_id = ToMessageID(name);
1105 if (message_id < 0)
1106 return WebString();
1107 return ReplaceStringPlaceholders(GetContentClient()->GetLocalizedString(
1108 message_id), value, NULL);
1111 WebString BlinkPlatformImpl::queryLocalizedString(
1112 WebLocalizedString::Name name,
1113 const WebString& value1,
1114 const WebString& value2) {
1115 int message_id = ToMessageID(name);
1116 if (message_id < 0)
1117 return WebString();
1118 std::vector<base::string16> values;
1119 values.reserve(2);
1120 values.push_back(value1);
1121 values.push_back(value2);
1122 return ReplaceStringPlaceholders(
1123 GetContentClient()->GetLocalizedString(message_id), values, NULL);
1126 double BlinkPlatformImpl::currentTime() {
1127 return base::Time::Now().ToDoubleT();
1130 double BlinkPlatformImpl::monotonicallyIncreasingTime() {
1131 return base::TimeTicks::Now().ToInternalValue() /
1132 static_cast<double>(base::Time::kMicrosecondsPerSecond);
1135 double BlinkPlatformImpl::systemTraceTime() {
1136 return (base::TraceTicks::Now() - base::TraceTicks()).InSecondsF();
1139 void BlinkPlatformImpl::cryptographicallyRandomValues(
1140 unsigned char* buffer, size_t length) {
1141 base::RandBytes(buffer, length);
1144 blink::WebGestureCurve* BlinkPlatformImpl::createFlingAnimationCurve(
1145 blink::WebGestureDevice device_source,
1146 const blink::WebFloatPoint& velocity,
1147 const blink::WebSize& cumulative_scroll) {
1148 return ui::WebGestureCurveImpl::CreateFromDefaultPlatformCurve(
1149 gfx::Vector2dF(velocity.x, velocity.y),
1150 gfx::Vector2dF(cumulative_scroll.width, cumulative_scroll.height),
1151 IsMainThread()).release();
1154 void BlinkPlatformImpl::didStartWorkerRunLoop() {
1155 WorkerTaskRunner* worker_task_runner = WorkerTaskRunner::Instance();
1156 worker_task_runner->OnWorkerRunLoopStarted();
1159 void BlinkPlatformImpl::didStopWorkerRunLoop() {
1160 WorkerTaskRunner* worker_task_runner = WorkerTaskRunner::Instance();
1161 worker_task_runner->OnWorkerRunLoopStopped();
1164 blink::WebCrypto* BlinkPlatformImpl::crypto() {
1165 return &web_crypto_;
1168 blink::WebGeofencingProvider* BlinkPlatformImpl::geofencingProvider() {
1169 return geofencing_provider_.get();
1172 blink::WebBluetooth* BlinkPlatformImpl::bluetooth() {
1173 return bluetooth_.get();
1176 blink::WebNotificationManager*
1177 BlinkPlatformImpl::notificationManager() {
1178 if (!thread_safe_sender_.get() || !notification_dispatcher_.get())
1179 return nullptr;
1181 return NotificationManager::ThreadSpecificInstance(
1182 thread_safe_sender_.get(),
1183 main_thread_task_runner_.get(),
1184 notification_dispatcher_.get());
1187 blink::WebPushProvider* BlinkPlatformImpl::pushProvider() {
1188 if (!thread_safe_sender_.get() || !push_dispatcher_.get())
1189 return nullptr;
1191 return PushProvider::ThreadSpecificInstance(thread_safe_sender_.get(),
1192 push_dispatcher_.get());
1195 blink::WebNavigatorConnectProvider*
1196 BlinkPlatformImpl::navigatorConnectProvider() {
1197 if (!thread_safe_sender_.get())
1198 return nullptr;
1200 return NavigatorConnectProvider::ThreadSpecificInstance(
1201 thread_safe_sender_.get(), main_thread_task_runner_);
1204 blink::WebPermissionClient* BlinkPlatformImpl::permissionClient() {
1205 if (!permission_client_.get())
1206 return nullptr;
1208 if (IsMainThread())
1209 return permission_client_.get();
1211 return PermissionDispatcherThreadProxy::GetThreadInstance(
1212 main_thread_task_runner_.get(), permission_client_.get());
1215 blink::WebSyncProvider* BlinkPlatformImpl::backgroundSyncProvider() {
1216 if (!sync_provider_.get())
1217 return nullptr;
1219 if (IsMainThread())
1220 return sync_provider_.get();
1222 return BackgroundSyncProviderThreadProxy::GetThreadInstance(
1223 main_thread_task_runner_.get(), sync_provider_.get());
1226 WebThemeEngine* BlinkPlatformImpl::themeEngine() {
1227 return &native_theme_engine_;
1230 WebFallbackThemeEngine* BlinkPlatformImpl::fallbackThemeEngine() {
1231 return &fallback_theme_engine_;
1234 blink::Platform::FileHandle BlinkPlatformImpl::databaseOpenFile(
1235 const blink::WebString& vfs_file_name, int desired_flags) {
1236 #if defined(OS_WIN)
1237 return INVALID_HANDLE_VALUE;
1238 #elif defined(OS_POSIX)
1239 return -1;
1240 #endif
1243 int BlinkPlatformImpl::databaseDeleteFile(
1244 const blink::WebString& vfs_file_name, bool sync_dir) {
1245 return -1;
1248 long BlinkPlatformImpl::databaseGetFileAttributes(
1249 const blink::WebString& vfs_file_name) {
1250 return 0;
1253 long long BlinkPlatformImpl::databaseGetFileSize(
1254 const blink::WebString& vfs_file_name) {
1255 return 0;
1258 long long BlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
1259 const blink::WebString& origin_identifier) {
1260 return 0;
1263 bool BlinkPlatformImpl::databaseSetFileSize(
1264 const blink::WebString& vfs_file_name, long long size) {
1265 return false;
1268 blink::WebString BlinkPlatformImpl::signedPublicKeyAndChallengeString(
1269 unsigned key_size_index,
1270 const blink::WebString& challenge,
1271 const blink::WebURL& url) {
1272 return blink::WebString("");
1275 static scoped_ptr<base::ProcessMetrics> CurrentProcessMetrics() {
1276 using base::ProcessMetrics;
1277 #if defined(OS_MACOSX)
1278 return scoped_ptr<ProcessMetrics>(
1279 // The default port provider is sufficient to get data for the current
1280 // process.
1281 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle(),
1282 NULL));
1283 #else
1284 return scoped_ptr<ProcessMetrics>(
1285 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle()));
1286 #endif
1289 static size_t getMemoryUsageMB(bool bypass_cache) {
1290 size_t current_mem_usage = 0;
1291 MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::GetInstance();
1292 if (!bypass_cache &&
1293 mem_usage_cache_singleton->IsCachedValueValid(&current_mem_usage))
1294 return current_mem_usage;
1296 current_mem_usage = GetMemoryUsageKB() >> 10;
1297 mem_usage_cache_singleton->SetMemoryValue(current_mem_usage);
1298 return current_mem_usage;
1301 size_t BlinkPlatformImpl::memoryUsageMB() {
1302 return getMemoryUsageMB(false);
1305 size_t BlinkPlatformImpl::actualMemoryUsageMB() {
1306 return getMemoryUsageMB(true);
1309 size_t BlinkPlatformImpl::physicalMemoryMB() {
1310 return static_cast<size_t>(base::SysInfo::AmountOfPhysicalMemoryMB());
1313 size_t BlinkPlatformImpl::virtualMemoryLimitMB() {
1314 return static_cast<size_t>(base::SysInfo::AmountOfVirtualMemoryMB());
1317 size_t BlinkPlatformImpl::numberOfProcessors() {
1318 return static_cast<size_t>(base::SysInfo::NumberOfProcessors());
1321 bool BlinkPlatformImpl::processMemorySizesInBytes(
1322 size_t* private_bytes,
1323 size_t* shared_bytes) {
1324 return CurrentProcessMetrics()->GetMemoryBytes(private_bytes, shared_bytes);
1327 bool BlinkPlatformImpl::memoryAllocatorWasteInBytes(size_t* size) {
1328 return base::allocator::GetAllocatorWasteSize(size);
1331 blink::WebDiscardableMemory*
1332 BlinkPlatformImpl::allocateAndLockDiscardableMemory(size_t bytes) {
1333 return content::WebDiscardableMemoryImpl::CreateLockedMemory(bytes).release();
1336 size_t BlinkPlatformImpl::maxDecodedImageBytes() {
1337 #if defined(OS_ANDROID)
1338 if (base::SysInfo::IsLowEndDevice()) {
1339 // Limit image decoded size to 3M pixels on low end devices.
1340 // 4 is maximum number of bytes per pixel.
1341 return 3 * 1024 * 1024 * 4;
1343 // For other devices, limit decoded image size based on the amount of physical
1344 // memory.
1345 // In some cases all physical memory is not accessible by Chromium, as it can
1346 // be reserved for direct use by certain hardware. Thus, we set the limit so
1347 // that 1.6GB of reported physical memory on a 2GB device is enough to set the
1348 // limit at 16M pixels, which is a desirable value since 4K*4K is a relatively
1349 // common texture size.
1350 return base::SysInfo::AmountOfPhysicalMemory() / 25;
1351 #else
1352 return noDecodedImageByteLimit;
1353 #endif
1356 uint32_t BlinkPlatformImpl::getUniqueIdForProcess() {
1357 // TODO(rickyz): Replace this with base::GetUniqueIdForProcess when that's
1358 // ready.
1359 return base::trace_event::TraceLog::GetInstance()->process_id();
1362 scoped_refptr<base::SingleThreadTaskRunner>
1363 BlinkPlatformImpl::MainTaskRunnerForCurrentThread() {
1364 if (main_thread_task_runner_.get() &&
1365 main_thread_task_runner_->BelongsToCurrentThread()) {
1366 return main_thread_task_runner_;
1367 } else {
1368 return base::ThreadTaskRunnerHandle::Get();
1372 bool BlinkPlatformImpl::IsMainThread() const {
1373 return main_thread_task_runner_.get() &&
1374 main_thread_task_runner_->BelongsToCurrentThread();
1377 WebString BlinkPlatformImpl::domCodeStringFromEnum(int dom_code) {
1378 return WebString::fromUTF8(ui::KeycodeConverter::DomCodeToCodeString(
1379 static_cast<ui::DomCode>(dom_code)));
1382 int BlinkPlatformImpl::domEnumFromCodeString(const WebString& code) {
1383 return static_cast<int>(ui::KeycodeConverter::CodeStringToDomCode(
1384 code.utf8().data()));
1387 } // namespace content