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