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