Removing uses of X11 native key events.
[chromium-blink-merge.git] / content / child / blink_platform_impl.cc
blobdc71511365116f2523697fe44f9a2cfe3eba1da0
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/memory/scoped_ptr.h"
15 #include "base/memory/singleton.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/metrics/sparse_histogram.h"
19 #include "base/metrics/stats_counters.h"
20 #include "base/process/process_metrics.h"
21 #include "base/rand_util.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/time/time.h"
29 #include "blink/public/resources/grit/blink_resources.h"
30 #include "content/app/resources/grit/content_resources.h"
31 #include "content/app/strings/grit/content_strings.h"
32 #include "content/child/child_thread.h"
33 #include "content/child/content_child_helpers.h"
34 #include "content/child/fling_curve_configuration.h"
35 #include "content/child/web_discardable_memory_impl.h"
36 #include "content/child/web_socket_stream_handle_impl.h"
37 #include "content/child/web_url_loader_impl.h"
38 #include "content/child/websocket_bridge.h"
39 #include "content/child/webthread_impl.h"
40 #include "content/child/worker_task_runner.h"
41 #include "content/public/common/content_client.h"
42 #include "net/base/data_url.h"
43 #include "net/base/mime_util.h"
44 #include "net/base/net_errors.h"
45 #include "net/base/net_util.h"
46 #include "third_party/WebKit/public/platform/WebConvertableToTraceFormat.h"
47 #include "third_party/WebKit/public/platform/WebData.h"
48 #include "third_party/WebKit/public/platform/WebString.h"
49 #include "third_party/WebKit/public/platform/WebURL.h"
50 #include "third_party/WebKit/public/platform/WebWaitableEvent.h"
51 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
52 #include "ui/base/layout.h"
54 #if defined(OS_ANDROID)
55 #include "content/child/fling_animator_impl_android.h"
56 #endif
58 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
59 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
60 #endif
62 using blink::WebData;
63 using blink::WebFallbackThemeEngine;
64 using blink::WebLocalizedString;
65 using blink::WebString;
66 using blink::WebSocketStreamHandle;
67 using blink::WebThemeEngine;
68 using blink::WebURL;
69 using blink::WebURLError;
70 using blink::WebURLLoader;
72 namespace content {
74 namespace {
76 class WebWaitableEventImpl : public blink::WebWaitableEvent {
77 public:
78 WebWaitableEventImpl() : impl_(new base::WaitableEvent(false, false)) {}
79 virtual ~WebWaitableEventImpl() {}
81 virtual void wait() { impl_->Wait(); }
82 virtual void signal() { impl_->Signal(); }
84 base::WaitableEvent* impl() {
85 return impl_.get();
88 private:
89 scoped_ptr<base::WaitableEvent> impl_;
90 DISALLOW_COPY_AND_ASSIGN(WebWaitableEventImpl);
93 // A simple class to cache the memory usage for a given amount of time.
94 class MemoryUsageCache {
95 public:
96 // Retrieves the Singleton.
97 static MemoryUsageCache* GetInstance() {
98 return Singleton<MemoryUsageCache>::get();
101 MemoryUsageCache() : memory_value_(0) { Init(); }
102 ~MemoryUsageCache() {}
104 void Init() {
105 const unsigned int kCacheSeconds = 1;
106 cache_valid_time_ = base::TimeDelta::FromSeconds(kCacheSeconds);
109 // Returns true if the cached value is fresh.
110 // Returns false if the cached value is stale, or if |cached_value| is NULL.
111 bool IsCachedValueValid(size_t* cached_value) {
112 base::AutoLock scoped_lock(lock_);
113 if (!cached_value)
114 return false;
115 if (base::Time::Now() - last_updated_time_ > cache_valid_time_)
116 return false;
117 *cached_value = memory_value_;
118 return true;
121 // Setter for |memory_value_|, refreshes |last_updated_time_|.
122 void SetMemoryValue(const size_t value) {
123 base::AutoLock scoped_lock(lock_);
124 memory_value_ = value;
125 last_updated_time_ = base::Time::Now();
128 private:
129 // The cached memory value.
130 size_t memory_value_;
132 // How long the cached value should remain valid.
133 base::TimeDelta cache_valid_time_;
135 // The last time the cached value was updated.
136 base::Time last_updated_time_;
138 base::Lock lock_;
141 class ConvertableToTraceFormatWrapper
142 : public base::debug::ConvertableToTraceFormat {
143 public:
144 explicit ConvertableToTraceFormatWrapper(
145 const blink::WebConvertableToTraceFormat& convertable)
146 : convertable_(convertable) {}
147 virtual void AppendAsTraceFormat(std::string* out) const OVERRIDE {
148 *out += convertable_.asTraceFormat().utf8();
151 private:
152 virtual ~ConvertableToTraceFormatWrapper() {}
154 blink::WebConvertableToTraceFormat convertable_;
157 bool isHostnameReservedIPAddress(const std::string& host) {
158 net::IPAddressNumber address;
159 if (!net::ParseURLHostnameToNumber(host, &address))
160 return false;
161 return net::IsIPAddressReserved(address);
164 } // namespace
166 static int ToMessageID(WebLocalizedString::Name name) {
167 switch (name) {
168 case WebLocalizedString::AXAMPMFieldText:
169 return IDS_AX_AM_PM_FIELD_TEXT;
170 case WebLocalizedString::AXButtonActionVerb:
171 return IDS_AX_BUTTON_ACTION_VERB;
172 case WebLocalizedString::AXCalendarShowMonthSelector:
173 return IDS_AX_CALENDAR_SHOW_MONTH_SELECTOR;
174 case WebLocalizedString::AXCalendarShowNextMonth:
175 return IDS_AX_CALENDAR_SHOW_NEXT_MONTH;
176 case WebLocalizedString::AXCalendarShowPreviousMonth:
177 return IDS_AX_CALENDAR_SHOW_PREVIOUS_MONTH;
178 case WebLocalizedString::AXCalendarWeekDescription:
179 return IDS_AX_CALENDAR_WEEK_DESCRIPTION;
180 case WebLocalizedString::AXCheckedCheckBoxActionVerb:
181 return IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB;
182 case WebLocalizedString::AXDateTimeFieldEmptyValueText:
183 return IDS_AX_DATE_TIME_FIELD_EMPTY_VALUE_TEXT;
184 case WebLocalizedString::AXDayOfMonthFieldText:
185 return IDS_AX_DAY_OF_MONTH_FIELD_TEXT;
186 case WebLocalizedString::AXHeadingText:
187 return IDS_AX_ROLE_HEADING;
188 case WebLocalizedString::AXHourFieldText:
189 return IDS_AX_HOUR_FIELD_TEXT;
190 case WebLocalizedString::AXImageMapText:
191 return IDS_AX_ROLE_IMAGE_MAP;
192 case WebLocalizedString::AXLinkActionVerb:
193 return IDS_AX_LINK_ACTION_VERB;
194 case WebLocalizedString::AXLinkText:
195 return IDS_AX_ROLE_LINK;
196 case WebLocalizedString::AXListMarkerText:
197 return IDS_AX_ROLE_LIST_MARKER;
198 case WebLocalizedString::AXMediaDefault:
199 return IDS_AX_MEDIA_DEFAULT;
200 case WebLocalizedString::AXMediaAudioElement:
201 return IDS_AX_MEDIA_AUDIO_ELEMENT;
202 case WebLocalizedString::AXMediaVideoElement:
203 return IDS_AX_MEDIA_VIDEO_ELEMENT;
204 case WebLocalizedString::AXMediaMuteButton:
205 return IDS_AX_MEDIA_MUTE_BUTTON;
206 case WebLocalizedString::AXMediaUnMuteButton:
207 return IDS_AX_MEDIA_UNMUTE_BUTTON;
208 case WebLocalizedString::AXMediaPlayButton:
209 return IDS_AX_MEDIA_PLAY_BUTTON;
210 case WebLocalizedString::AXMediaPauseButton:
211 return IDS_AX_MEDIA_PAUSE_BUTTON;
212 case WebLocalizedString::AXMediaSlider:
213 return IDS_AX_MEDIA_SLIDER;
214 case WebLocalizedString::AXMediaSliderThumb:
215 return IDS_AX_MEDIA_SLIDER_THUMB;
216 case WebLocalizedString::AXMediaCurrentTimeDisplay:
217 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY;
218 case WebLocalizedString::AXMediaTimeRemainingDisplay:
219 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY;
220 case WebLocalizedString::AXMediaStatusDisplay:
221 return IDS_AX_MEDIA_STATUS_DISPLAY;
222 case WebLocalizedString::AXMediaEnterFullscreenButton:
223 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON;
224 case WebLocalizedString::AXMediaExitFullscreenButton:
225 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON;
226 case WebLocalizedString::AXMediaShowClosedCaptionsButton:
227 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON;
228 case WebLocalizedString::AXMediaHideClosedCaptionsButton:
229 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON;
230 case WebLocalizedString::AxMediaCastOffButton:
231 return IDS_AX_MEDIA_CAST_OFF_BUTTON;
232 case WebLocalizedString::AxMediaCastOnButton:
233 return IDS_AX_MEDIA_CAST_ON_BUTTON;
234 case WebLocalizedString::AXMediaAudioElementHelp:
235 return IDS_AX_MEDIA_AUDIO_ELEMENT_HELP;
236 case WebLocalizedString::AXMediaVideoElementHelp:
237 return IDS_AX_MEDIA_VIDEO_ELEMENT_HELP;
238 case WebLocalizedString::AXMediaMuteButtonHelp:
239 return IDS_AX_MEDIA_MUTE_BUTTON_HELP;
240 case WebLocalizedString::AXMediaUnMuteButtonHelp:
241 return IDS_AX_MEDIA_UNMUTE_BUTTON_HELP;
242 case WebLocalizedString::AXMediaPlayButtonHelp:
243 return IDS_AX_MEDIA_PLAY_BUTTON_HELP;
244 case WebLocalizedString::AXMediaPauseButtonHelp:
245 return IDS_AX_MEDIA_PAUSE_BUTTON_HELP;
246 case WebLocalizedString::AXMediaSliderHelp:
247 return IDS_AX_MEDIA_SLIDER_HELP;
248 case WebLocalizedString::AXMediaSliderThumbHelp:
249 return IDS_AX_MEDIA_SLIDER_THUMB_HELP;
250 case WebLocalizedString::AXMediaCurrentTimeDisplayHelp:
251 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY_HELP;
252 case WebLocalizedString::AXMediaTimeRemainingDisplayHelp:
253 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY_HELP;
254 case WebLocalizedString::AXMediaStatusDisplayHelp:
255 return IDS_AX_MEDIA_STATUS_DISPLAY_HELP;
256 case WebLocalizedString::AXMediaEnterFullscreenButtonHelp:
257 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON_HELP;
258 case WebLocalizedString::AXMediaExitFullscreenButtonHelp:
259 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON_HELP;
260 case WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp:
261 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON_HELP;
262 case WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp:
263 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON_HELP;
264 case WebLocalizedString::AxMediaCastOffButtonHelp:
265 return IDS_AX_MEDIA_CAST_OFF_BUTTON_HELP;
266 case WebLocalizedString::AxMediaCastOnButtonHelp:
267 return IDS_AX_MEDIA_CAST_ON_BUTTON_HELP;
268 case WebLocalizedString::AXMillisecondFieldText:
269 return IDS_AX_MILLISECOND_FIELD_TEXT;
270 case WebLocalizedString::AXMinuteFieldText:
271 return IDS_AX_MINUTE_FIELD_TEXT;
272 case WebLocalizedString::AXMonthFieldText:
273 return IDS_AX_MONTH_FIELD_TEXT;
274 case WebLocalizedString::AXRadioButtonActionVerb:
275 return IDS_AX_RADIO_BUTTON_ACTION_VERB;
276 case WebLocalizedString::AXSecondFieldText:
277 return IDS_AX_SECOND_FIELD_TEXT;
278 case WebLocalizedString::AXTextFieldActionVerb:
279 return IDS_AX_TEXT_FIELD_ACTION_VERB;
280 case WebLocalizedString::AXUncheckedCheckBoxActionVerb:
281 return IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB;
282 case WebLocalizedString::AXWebAreaText:
283 return IDS_AX_ROLE_WEB_AREA;
284 case WebLocalizedString::AXWeekOfYearFieldText:
285 return IDS_AX_WEEK_OF_YEAR_FIELD_TEXT;
286 case WebLocalizedString::AXYearFieldText:
287 return IDS_AX_YEAR_FIELD_TEXT;
288 case WebLocalizedString::CalendarClear:
289 return IDS_FORM_CALENDAR_CLEAR;
290 case WebLocalizedString::CalendarToday:
291 return IDS_FORM_CALENDAR_TODAY;
292 case WebLocalizedString::DateFormatDayInMonthLabel:
293 return IDS_FORM_DATE_FORMAT_DAY_IN_MONTH;
294 case WebLocalizedString::DateFormatMonthLabel:
295 return IDS_FORM_DATE_FORMAT_MONTH;
296 case WebLocalizedString::DateFormatYearLabel:
297 return IDS_FORM_DATE_FORMAT_YEAR;
298 case WebLocalizedString::DetailsLabel:
299 return IDS_DETAILS_WITHOUT_SUMMARY_LABEL;
300 case WebLocalizedString::FileButtonChooseFileLabel:
301 return IDS_FORM_FILE_BUTTON_LABEL;
302 case WebLocalizedString::FileButtonChooseMultipleFilesLabel:
303 return IDS_FORM_MULTIPLE_FILES_BUTTON_LABEL;
304 case WebLocalizedString::FileButtonNoFileSelectedLabel:
305 return IDS_FORM_FILE_NO_FILE_LABEL;
306 case WebLocalizedString::InputElementAltText:
307 return IDS_FORM_INPUT_ALT;
308 case WebLocalizedString::KeygenMenuHighGradeKeySize:
309 return IDS_KEYGEN_HIGH_GRADE_KEY;
310 case WebLocalizedString::KeygenMenuMediumGradeKeySize:
311 return IDS_KEYGEN_MED_GRADE_KEY;
312 case WebLocalizedString::MissingPluginText:
313 return IDS_PLUGIN_INITIALIZATION_ERROR;
314 case WebLocalizedString::MultipleFileUploadText:
315 return IDS_FORM_FILE_MULTIPLE_UPLOAD;
316 case WebLocalizedString::OtherColorLabel:
317 return IDS_FORM_OTHER_COLOR_LABEL;
318 case WebLocalizedString::OtherDateLabel:
319 return IDS_FORM_OTHER_DATE_LABEL;
320 case WebLocalizedString::OtherMonthLabel:
321 return IDS_FORM_OTHER_MONTH_LABEL;
322 case WebLocalizedString::OtherTimeLabel:
323 return IDS_FORM_OTHER_TIME_LABEL;
324 case WebLocalizedString::OtherWeekLabel:
325 return IDS_FORM_OTHER_WEEK_LABEL;
326 case WebLocalizedString::PlaceholderForDayOfMonthField:
327 return IDS_FORM_PLACEHOLDER_FOR_DAY_OF_MONTH_FIELD;
328 case WebLocalizedString::PlaceholderForMonthField:
329 return IDS_FORM_PLACEHOLDER_FOR_MONTH_FIELD;
330 case WebLocalizedString::PlaceholderForYearField:
331 return IDS_FORM_PLACEHOLDER_FOR_YEAR_FIELD;
332 case WebLocalizedString::ResetButtonDefaultLabel:
333 return IDS_FORM_RESET_LABEL;
334 case WebLocalizedString::SearchableIndexIntroduction:
335 return IDS_SEARCHABLE_INDEX_INTRO;
336 case WebLocalizedString::SearchMenuClearRecentSearchesText:
337 return IDS_RECENT_SEARCHES_CLEAR;
338 case WebLocalizedString::SearchMenuNoRecentSearchesText:
339 return IDS_RECENT_SEARCHES_NONE;
340 case WebLocalizedString::SearchMenuRecentSearchesText:
341 return IDS_RECENT_SEARCHES;
342 case WebLocalizedString::SelectMenuListText:
343 return IDS_FORM_SELECT_MENU_LIST_TEXT;
344 case WebLocalizedString::SubmitButtonDefaultLabel:
345 return IDS_FORM_SUBMIT_LABEL;
346 case WebLocalizedString::ThisMonthButtonLabel:
347 return IDS_FORM_THIS_MONTH_LABEL;
348 case WebLocalizedString::ThisWeekButtonLabel:
349 return IDS_FORM_THIS_WEEK_LABEL;
350 case WebLocalizedString::ValidationBadInputForDateTime:
351 return IDS_FORM_VALIDATION_BAD_INPUT_DATETIME;
352 case WebLocalizedString::ValidationBadInputForNumber:
353 return IDS_FORM_VALIDATION_BAD_INPUT_NUMBER;
354 case WebLocalizedString::ValidationPatternMismatch:
355 return IDS_FORM_VALIDATION_PATTERN_MISMATCH;
356 case WebLocalizedString::ValidationRangeOverflow:
357 return IDS_FORM_VALIDATION_RANGE_OVERFLOW;
358 case WebLocalizedString::ValidationRangeOverflowDateTime:
359 return IDS_FORM_VALIDATION_RANGE_OVERFLOW_DATETIME;
360 case WebLocalizedString::ValidationRangeUnderflow:
361 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW;
362 case WebLocalizedString::ValidationRangeUnderflowDateTime:
363 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW_DATETIME;
364 case WebLocalizedString::ValidationStepMismatch:
365 return IDS_FORM_VALIDATION_STEP_MISMATCH;
366 case WebLocalizedString::ValidationStepMismatchCloseToLimit:
367 return IDS_FORM_VALIDATION_STEP_MISMATCH_CLOSE_TO_LIMIT;
368 case WebLocalizedString::ValidationTooLong:
369 return IDS_FORM_VALIDATION_TOO_LONG;
370 case WebLocalizedString::ValidationTypeMismatch:
371 return IDS_FORM_VALIDATION_TYPE_MISMATCH;
372 case WebLocalizedString::ValidationTypeMismatchForEmail:
373 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL;
374 case WebLocalizedString::ValidationTypeMismatchForEmailEmpty:
375 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY;
376 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyDomain:
377 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_DOMAIN;
378 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyLocal:
379 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_LOCAL;
380 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDomain:
381 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOMAIN;
382 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots:
383 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOTS;
384 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidLocal:
385 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_LOCAL;
386 case WebLocalizedString::ValidationTypeMismatchForEmailNoAtSign:
387 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_NO_AT_SIGN;
388 case WebLocalizedString::ValidationTypeMismatchForMultipleEmail:
389 return IDS_FORM_VALIDATION_TYPE_MISMATCH_MULTIPLE_EMAIL;
390 case WebLocalizedString::ValidationTypeMismatchForURL:
391 return IDS_FORM_VALIDATION_TYPE_MISMATCH_URL;
392 case WebLocalizedString::ValidationValueMissing:
393 return IDS_FORM_VALIDATION_VALUE_MISSING;
394 case WebLocalizedString::ValidationValueMissingForCheckbox:
395 return IDS_FORM_VALIDATION_VALUE_MISSING_CHECKBOX;
396 case WebLocalizedString::ValidationValueMissingForFile:
397 return IDS_FORM_VALIDATION_VALUE_MISSING_FILE;
398 case WebLocalizedString::ValidationValueMissingForMultipleFile:
399 return IDS_FORM_VALIDATION_VALUE_MISSING_MULTIPLE_FILE;
400 case WebLocalizedString::ValidationValueMissingForRadio:
401 return IDS_FORM_VALIDATION_VALUE_MISSING_RADIO;
402 case WebLocalizedString::ValidationValueMissingForSelect:
403 return IDS_FORM_VALIDATION_VALUE_MISSING_SELECT;
404 case WebLocalizedString::WeekFormatTemplate:
405 return IDS_FORM_INPUT_WEEK_TEMPLATE;
406 case WebLocalizedString::WeekNumberLabel:
407 return IDS_FORM_WEEK_NUMBER_LABEL;
408 // This "default:" line exists to avoid compile warnings about enum
409 // coverage when we add a new symbol to WebLocalizedString.h in WebKit.
410 // After a planned WebKit patch is landed, we need to add a case statement
411 // for the added symbol here.
412 default:
413 break;
415 return -1;
418 BlinkPlatformImpl::BlinkPlatformImpl()
419 : main_loop_(base::MessageLoop::current()),
420 shared_timer_func_(NULL),
421 shared_timer_fire_time_(0.0),
422 shared_timer_fire_time_was_set_while_suspended_(false),
423 shared_timer_suspended_(0),
424 fling_curve_configuration_(new FlingCurveConfiguration),
425 current_thread_slot_(&DestroyCurrentThread) {}
427 BlinkPlatformImpl::~BlinkPlatformImpl() {
430 WebURLLoader* BlinkPlatformImpl::createURLLoader() {
431 ChildThread* child_thread = ChildThread::current();
432 // There may be no child thread in RenderViewTests. These tests can still use
433 // data URLs to bypass the ResourceDispatcher.
434 return new WebURLLoaderImpl(
435 child_thread ? child_thread->resource_dispatcher() : NULL);
438 WebSocketStreamHandle* BlinkPlatformImpl::createSocketStreamHandle() {
439 return new WebSocketStreamHandleImpl;
442 blink::WebSocketHandle* BlinkPlatformImpl::createWebSocketHandle() {
443 return new WebSocketBridge;
446 WebString BlinkPlatformImpl::userAgent() {
447 return WebString::fromUTF8(GetContentClient()->GetUserAgent());
450 WebData BlinkPlatformImpl::parseDataURL(const WebURL& url,
451 WebString& mimetype_out,
452 WebString& charset_out) {
453 std::string mime_type, char_set, data;
454 if (net::DataURL::Parse(url, &mime_type, &char_set, &data)
455 && net::IsSupportedMimeType(mime_type)) {
456 mimetype_out = WebString::fromUTF8(mime_type);
457 charset_out = WebString::fromUTF8(char_set);
458 return data;
460 return WebData();
463 WebURLError BlinkPlatformImpl::cancelledError(
464 const WebURL& unreachableURL) const {
465 return WebURLLoaderImpl::CreateError(unreachableURL, false, net::ERR_ABORTED);
468 bool BlinkPlatformImpl::isReservedIPAddress(
469 const blink::WebSecurityOrigin& securityOrigin) const {
470 return isHostnameReservedIPAddress(securityOrigin.host().utf8());
473 bool BlinkPlatformImpl::isReservedIPAddress(const blink::WebURL& url) const {
474 return isHostnameReservedIPAddress(GURL(url).host());
477 blink::WebThread* BlinkPlatformImpl::createThread(const char* name) {
478 return new WebThreadImpl(name);
481 blink::WebThread* BlinkPlatformImpl::currentThread() {
482 WebThreadImplForMessageLoop* thread =
483 static_cast<WebThreadImplForMessageLoop*>(current_thread_slot_.Get());
484 if (thread)
485 return (thread);
487 scoped_refptr<base::MessageLoopProxy> message_loop =
488 base::MessageLoopProxy::current();
489 if (!message_loop.get())
490 return NULL;
492 thread = new WebThreadImplForMessageLoop(message_loop.get());
493 current_thread_slot_.Set(thread);
494 return thread;
497 blink::WebWaitableEvent* BlinkPlatformImpl::createWaitableEvent() {
498 return new WebWaitableEventImpl();
501 blink::WebWaitableEvent* BlinkPlatformImpl::waitMultipleEvents(
502 const blink::WebVector<blink::WebWaitableEvent*>& web_events) {
503 std::vector<base::WaitableEvent*> events;
504 for (size_t i = 0; i < web_events.size(); ++i)
505 events.push_back(static_cast<WebWaitableEventImpl*>(web_events[i])->impl());
506 size_t idx = base::WaitableEvent::WaitMany(
507 vector_as_array(&events), events.size());
508 DCHECK_LT(idx, web_events.size());
509 return web_events[idx];
512 void BlinkPlatformImpl::decrementStatsCounter(const char* name) {
513 base::StatsCounter(name).Decrement();
516 void BlinkPlatformImpl::incrementStatsCounter(const char* name) {
517 base::StatsCounter(name).Increment();
520 void BlinkPlatformImpl::histogramCustomCounts(
521 const char* name, int sample, int min, int max, int bucket_count) {
522 // Copied from histogram macro, but without the static variable caching
523 // the histogram because name is dynamic.
524 base::HistogramBase* counter =
525 base::Histogram::FactoryGet(name, min, max, bucket_count,
526 base::HistogramBase::kUmaTargetedHistogramFlag);
527 DCHECK_EQ(name, counter->histogram_name());
528 counter->Add(sample);
531 void BlinkPlatformImpl::histogramEnumeration(
532 const char* name, int sample, int boundary_value) {
533 // Copied from histogram macro, but without the static variable caching
534 // the histogram because name is dynamic.
535 base::HistogramBase* counter =
536 base::LinearHistogram::FactoryGet(name, 1, boundary_value,
537 boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
538 DCHECK_EQ(name, counter->histogram_name());
539 counter->Add(sample);
542 void BlinkPlatformImpl::histogramSparse(const char* name, int sample) {
543 // For sparse histograms, we can use the macro, as it does not incorporate a
544 // static.
545 UMA_HISTOGRAM_SPARSE_SLOWLY(name, sample);
548 const unsigned char* BlinkPlatformImpl::getTraceCategoryEnabledFlag(
549 const char* category_group) {
550 return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(category_group);
553 long* BlinkPlatformImpl::getTraceSamplingState(
554 const unsigned thread_bucket) {
555 switch (thread_bucket) {
556 case 0:
557 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(0));
558 case 1:
559 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(1));
560 case 2:
561 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(2));
562 default:
563 NOTREACHED() << "Unknown thread bucket type.";
565 return NULL;
568 COMPILE_ASSERT(
569 sizeof(blink::Platform::TraceEventHandle) ==
570 sizeof(base::debug::TraceEventHandle),
571 TraceEventHandle_types_must_be_same_size);
573 blink::Platform::TraceEventHandle BlinkPlatformImpl::addTraceEvent(
574 char phase,
575 const unsigned char* category_group_enabled,
576 const char* name,
577 unsigned long long id,
578 int num_args,
579 const char** arg_names,
580 const unsigned char* arg_types,
581 const unsigned long long* arg_values,
582 unsigned char flags) {
583 base::debug::TraceEventHandle handle = TRACE_EVENT_API_ADD_TRACE_EVENT(
584 phase, category_group_enabled, name, id,
585 num_args, arg_names, arg_types, arg_values, NULL, flags);
586 blink::Platform::TraceEventHandle result;
587 memcpy(&result, &handle, sizeof(result));
588 return result;
591 blink::Platform::TraceEventHandle BlinkPlatformImpl::addTraceEvent(
592 char phase,
593 const unsigned char* category_group_enabled,
594 const char* name,
595 unsigned long long id,
596 int num_args,
597 const char** arg_names,
598 const unsigned char* arg_types,
599 const unsigned long long* arg_values,
600 const blink::WebConvertableToTraceFormat* convertable_values,
601 unsigned char flags) {
602 scoped_refptr<base::debug::ConvertableToTraceFormat> convertable_wrappers[2];
603 if (convertable_values) {
604 size_t size = std::min(static_cast<size_t>(num_args),
605 arraysize(convertable_wrappers));
606 for (size_t i = 0; i < size; ++i) {
607 if (arg_types[i] == TRACE_VALUE_TYPE_CONVERTABLE) {
608 convertable_wrappers[i] =
609 new ConvertableToTraceFormatWrapper(convertable_values[i]);
613 base::debug::TraceEventHandle handle =
614 TRACE_EVENT_API_ADD_TRACE_EVENT(phase,
615 category_group_enabled,
616 name,
618 num_args,
619 arg_names,
620 arg_types,
621 arg_values,
622 convertable_wrappers,
623 flags);
624 blink::Platform::TraceEventHandle result;
625 memcpy(&result, &handle, sizeof(result));
626 return result;
629 void BlinkPlatformImpl::updateTraceEventDuration(
630 const unsigned char* category_group_enabled,
631 const char* name,
632 TraceEventHandle handle) {
633 base::debug::TraceEventHandle traceEventHandle;
634 memcpy(&traceEventHandle, &handle, sizeof(handle));
635 TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(
636 category_group_enabled, name, traceEventHandle);
639 namespace {
641 WebData loadAudioSpatializationResource(const char* name) {
642 #ifdef IDR_AUDIO_SPATIALIZATION_COMPOSITE
643 if (!strcmp(name, "Composite")) {
644 base::StringPiece resource = GetContentClient()->GetDataResource(
645 IDR_AUDIO_SPATIALIZATION_COMPOSITE, ui::SCALE_FACTOR_NONE);
646 return WebData(resource.data(), resource.size());
648 #endif
650 #ifdef IDR_AUDIO_SPATIALIZATION_T000_P000
651 const size_t kExpectedSpatializationNameLength = 31;
652 if (strlen(name) != kExpectedSpatializationNameLength) {
653 return WebData();
656 // Extract the azimuth and elevation from the resource name.
657 int azimuth = 0;
658 int elevation = 0;
659 int values_parsed =
660 sscanf(name, "IRC_Composite_C_R0195_T%3d_P%3d", &azimuth, &elevation);
661 if (values_parsed != 2) {
662 return WebData();
665 // The resource index values go through the elevations first, then azimuths.
666 const int kAngleSpacing = 15;
668 // 0 <= elevation <= 90 (or 315 <= elevation <= 345)
669 // in increments of 15 degrees.
670 int elevation_index =
671 elevation <= 90 ? elevation / kAngleSpacing :
672 7 + (elevation - 315) / kAngleSpacing;
673 bool is_elevation_index_good = 0 <= elevation_index && elevation_index < 10;
675 // 0 <= azimuth < 360 in increments of 15 degrees.
676 int azimuth_index = azimuth / kAngleSpacing;
677 bool is_azimuth_index_good = 0 <= azimuth_index && azimuth_index < 24;
679 const int kNumberOfElevations = 10;
680 const int kNumberOfAudioResources = 240;
681 int resource_index = kNumberOfElevations * azimuth_index + elevation_index;
682 bool is_resource_index_good = 0 <= resource_index &&
683 resource_index < kNumberOfAudioResources;
685 if (is_azimuth_index_good && is_elevation_index_good &&
686 is_resource_index_good) {
687 const int kFirstAudioResourceIndex = IDR_AUDIO_SPATIALIZATION_T000_P000;
688 base::StringPiece resource = GetContentClient()->GetDataResource(
689 kFirstAudioResourceIndex + resource_index, ui::SCALE_FACTOR_NONE);
690 return WebData(resource.data(), resource.size());
692 #endif // IDR_AUDIO_SPATIALIZATION_T000_P000
694 NOTREACHED();
695 return WebData();
698 struct DataResource {
699 const char* name;
700 int id;
701 ui::ScaleFactor scale_factor;
704 const DataResource kDataResources[] = {
705 { "missingImage", IDR_BROKENIMAGE, ui::SCALE_FACTOR_100P },
706 { "missingImage@2x", IDR_BROKENIMAGE, ui::SCALE_FACTOR_200P },
707 { "mediaplayerPause", IDR_MEDIAPLAYER_PAUSE_BUTTON, ui::SCALE_FACTOR_100P },
708 { "mediaplayerPauseHover",
709 IDR_MEDIAPLAYER_PAUSE_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
710 { "mediaplayerPauseDown",
711 IDR_MEDIAPLAYER_PAUSE_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
712 { "mediaplayerPlay", IDR_MEDIAPLAYER_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
713 { "mediaplayerPlayHover",
714 IDR_MEDIAPLAYER_PLAY_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
715 { "mediaplayerPlayDown",
716 IDR_MEDIAPLAYER_PLAY_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
717 { "mediaplayerPlayDisabled",
718 IDR_MEDIAPLAYER_PLAY_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
719 { "mediaplayerSoundLevel3",
720 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON, ui::SCALE_FACTOR_100P },
721 { "mediaplayerSoundLevel3Hover",
722 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
723 { "mediaplayerSoundLevel3Down",
724 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
725 { "mediaplayerSoundLevel2",
726 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON, ui::SCALE_FACTOR_100P },
727 { "mediaplayerSoundLevel2Hover",
728 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
729 { "mediaplayerSoundLevel2Down",
730 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
731 { "mediaplayerSoundLevel1",
732 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON, ui::SCALE_FACTOR_100P },
733 { "mediaplayerSoundLevel1Hover",
734 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
735 { "mediaplayerSoundLevel1Down",
736 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
737 { "mediaplayerSoundLevel0",
738 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON, ui::SCALE_FACTOR_100P },
739 { "mediaplayerSoundLevel0Hover",
740 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
741 { "mediaplayerSoundLevel0Down",
742 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
743 { "mediaplayerSoundDisabled",
744 IDR_MEDIAPLAYER_SOUND_DISABLED, ui::SCALE_FACTOR_100P },
745 { "mediaplayerSliderThumb",
746 IDR_MEDIAPLAYER_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
747 { "mediaplayerSliderThumbHover",
748 IDR_MEDIAPLAYER_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
749 { "mediaplayerSliderThumbDown",
750 IDR_MEDIAPLAYER_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
751 { "mediaplayerVolumeSliderThumb",
752 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
753 { "mediaplayerVolumeSliderThumbHover",
754 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
755 { "mediaplayerVolumeSliderThumbDown",
756 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
757 { "mediaplayerVolumeSliderThumbDisabled",
758 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DISABLED, ui::SCALE_FACTOR_100P },
759 { "mediaplayerClosedCaption",
760 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON, ui::SCALE_FACTOR_100P },
761 { "mediaplayerClosedCaptionHover",
762 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
763 { "mediaplayerClosedCaptionDown",
764 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
765 { "mediaplayerClosedCaptionDisabled",
766 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
767 { "mediaplayerFullscreen",
768 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON, ui::SCALE_FACTOR_100P },
769 { "mediaplayerFullscreenHover",
770 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
771 { "mediaplayerFullscreenDown",
772 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
773 { "mediaplayerCastOff",
774 IDR_MEDIAPLAYER_CAST_BUTTON_OFF, ui::SCALE_FACTOR_100P },
775 { "mediaplayerCastOn",
776 IDR_MEDIAPLAYER_CAST_BUTTON_ON, ui::SCALE_FACTOR_100P },
777 { "mediaplayerFullscreenDisabled",
778 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
779 { "mediaplayerOverlayPlay",
780 IDR_MEDIAPLAYER_OVERLAY_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
781 #if defined(OS_MACOSX)
782 { "overhangPattern", IDR_OVERHANG_PATTERN, ui::SCALE_FACTOR_100P },
783 { "overhangShadow", IDR_OVERHANG_SHADOW, ui::SCALE_FACTOR_100P },
784 #endif
785 { "panIcon", IDR_PAN_SCROLL_ICON, ui::SCALE_FACTOR_100P },
786 { "searchCancel", IDR_SEARCH_CANCEL, ui::SCALE_FACTOR_100P },
787 { "searchCancelPressed", IDR_SEARCH_CANCEL_PRESSED, ui::SCALE_FACTOR_100P },
788 { "searchMagnifier", IDR_SEARCH_MAGNIFIER, ui::SCALE_FACTOR_100P },
789 { "searchMagnifierResults",
790 IDR_SEARCH_MAGNIFIER_RESULTS, ui::SCALE_FACTOR_100P },
791 { "textAreaResizeCorner", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_100P },
792 { "textAreaResizeCorner@2x", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_200P },
793 { "generatePassword", IDR_PASSWORD_GENERATION_ICON, ui::SCALE_FACTOR_100P },
794 { "generatePasswordHover",
795 IDR_PASSWORD_GENERATION_ICON_HOVER, ui::SCALE_FACTOR_100P },
796 { "html.css", IDR_UASTYLE_HTML_CSS, ui::SCALE_FACTOR_NONE },
797 { "quirks.css", IDR_UASTYLE_QUIRKS_CSS, ui::SCALE_FACTOR_NONE },
798 { "view-source.css", IDR_UASTYLE_VIEW_SOURCE_CSS, ui::SCALE_FACTOR_NONE },
799 { "themeChromium.css", IDR_UASTYLE_THEME_CHROMIUM_CSS,
800 ui::SCALE_FACTOR_NONE },
801 #if defined(OS_ANDROID)
802 { "themeChromiumAndroid.css", IDR_UASTYLE_THEME_CHROMIUM_ANDROID_CSS,
803 ui::SCALE_FACTOR_NONE },
804 { "mediaControlsAndroid.css", IDR_UASTYLE_MEDIA_CONTROLS_ANDROID_CSS,
805 ui::SCALE_FACTOR_NONE },
806 #endif
807 #if !defined(OS_WIN)
808 { "themeChromiumLinux.css", IDR_UASTYLE_THEME_CHROMIUM_LINUX_CSS,
809 ui::SCALE_FACTOR_NONE },
810 #endif
811 { "themeChromiumSkia.css", IDR_UASTYLE_THEME_CHROMIUM_SKIA_CSS,
812 ui::SCALE_FACTOR_NONE },
813 { "themeInputMultipleFields.css",
814 IDR_UASTYLE_THEME_INPUT_MULTIPLE_FIELDS_CSS, ui::SCALE_FACTOR_NONE },
815 #if defined(OS_MACOSX)
816 { "themeMac.css", IDR_UASTYLE_THEME_MAC_CSS, ui::SCALE_FACTOR_NONE },
817 #endif
818 { "themeWin.css", IDR_UASTYLE_THEME_WIN_CSS, ui::SCALE_FACTOR_NONE },
819 { "themeWinQuirks.css", IDR_UASTYLE_THEME_WIN_QUIRKS_CSS,
820 ui::SCALE_FACTOR_NONE },
821 { "svg.css", IDR_UASTYLE_SVG_CSS, ui::SCALE_FACTOR_NONE},
822 { "navigationTransitions.css", IDR_UASTYLE_NAVIGATION_TRANSITIONS_CSS,
823 ui::SCALE_FACTOR_NONE },
824 { "mathml.css", IDR_UASTYLE_MATHML_CSS, ui::SCALE_FACTOR_NONE},
825 { "mediaControls.css", IDR_UASTYLE_MEDIA_CONTROLS_CSS,
826 ui::SCALE_FACTOR_NONE },
827 { "fullscreen.css", IDR_UASTYLE_FULLSCREEN_CSS, ui::SCALE_FACTOR_NONE},
828 { "xhtmlmp.css", IDR_UASTYLE_XHTMLMP_CSS, ui::SCALE_FACTOR_NONE},
829 { "viewportAndroid.css", IDR_UASTYLE_VIEWPORT_ANDROID_CSS,
830 ui::SCALE_FACTOR_NONE},
831 { "InspectorOverlayPage.html", IDR_INSPECTOR_OVERLAY_PAGE_HTML,
832 ui::SCALE_FACTOR_NONE },
833 { "InjectedScriptCanvasModuleSource.js",
834 IDR_INSPECTOR_INJECTED_SCRIPT_CANVAS_MODULE_SOURCE_JS,
835 ui::SCALE_FACTOR_NONE },
836 { "InjectedScriptSource.js", IDR_INSPECTOR_INJECTED_SCRIPT_SOURCE_JS,
837 ui::SCALE_FACTOR_NONE },
838 { "DebuggerScriptSource.js", IDR_INSPECTOR_DEBUGGER_SCRIPT_SOURCE_JS,
839 ui::SCALE_FACTOR_NONE },
840 { "DocumentXMLTreeViewer.js", IDR_PRIVATE_SCRIPT_DOCUMENTXMLTREEVIEWER_JS,
841 ui::SCALE_FACTOR_NONE },
842 { "HTMLMarqueeElement.js", IDR_PRIVATE_SCRIPT_HTMLMARQUEEELEMENT_JS,
843 ui::SCALE_FACTOR_NONE },
844 { "PluginPlaceholderElement.js",
845 IDR_PRIVATE_SCRIPT_PLUGINPLACEHOLDERELEMENT_JS, ui::SCALE_FACTOR_NONE },
846 { "PrivateScriptRunner.js", IDR_PRIVATE_SCRIPT_PRIVATESCRIPTRUNNER_JS,
847 ui::SCALE_FACTOR_NONE },
848 #ifdef IDR_PICKER_COMMON_JS
849 { "pickerCommon.js", IDR_PICKER_COMMON_JS, ui::SCALE_FACTOR_NONE },
850 { "pickerCommon.css", IDR_PICKER_COMMON_CSS, ui::SCALE_FACTOR_NONE },
851 { "calendarPicker.js", IDR_CALENDAR_PICKER_JS, ui::SCALE_FACTOR_NONE },
852 { "calendarPicker.css", IDR_CALENDAR_PICKER_CSS, ui::SCALE_FACTOR_NONE },
853 { "pickerButton.css", IDR_PICKER_BUTTON_CSS, ui::SCALE_FACTOR_NONE },
854 { "suggestionPicker.js", IDR_SUGGESTION_PICKER_JS, ui::SCALE_FACTOR_NONE },
855 { "suggestionPicker.css", IDR_SUGGESTION_PICKER_CSS, ui::SCALE_FACTOR_NONE },
856 { "colorSuggestionPicker.js",
857 IDR_COLOR_SUGGESTION_PICKER_JS, ui::SCALE_FACTOR_NONE },
858 { "colorSuggestionPicker.css",
859 IDR_COLOR_SUGGESTION_PICKER_CSS, ui::SCALE_FACTOR_NONE },
860 #endif
863 } // namespace
865 WebData BlinkPlatformImpl::loadResource(const char* name) {
866 // Some clients will call into this method with an empty |name| when they have
867 // optional resources. For example, the PopupMenuChromium code can have icons
868 // for some Autofill items but not for others.
869 if (!strlen(name))
870 return WebData();
872 // Check the name prefix to see if it's an audio resource.
873 if (StartsWithASCII(name, "IRC_Composite", true) ||
874 StartsWithASCII(name, "Composite", true))
875 return loadAudioSpatializationResource(name);
877 // TODO(flackr): We should use a better than linear search here, a trie would
878 // be ideal.
879 for (size_t i = 0; i < arraysize(kDataResources); ++i) {
880 if (!strcmp(name, kDataResources[i].name)) {
881 base::StringPiece resource = GetContentClient()->GetDataResource(
882 kDataResources[i].id, kDataResources[i].scale_factor);
883 return WebData(resource.data(), resource.size());
887 NOTREACHED() << "Unknown image resource " << name;
888 return WebData();
891 WebString BlinkPlatformImpl::queryLocalizedString(
892 WebLocalizedString::Name name) {
893 int message_id = ToMessageID(name);
894 if (message_id < 0)
895 return WebString();
896 return GetContentClient()->GetLocalizedString(message_id);
899 WebString BlinkPlatformImpl::queryLocalizedString(
900 WebLocalizedString::Name name, int numeric_value) {
901 return queryLocalizedString(name, base::IntToString16(numeric_value));
904 WebString BlinkPlatformImpl::queryLocalizedString(
905 WebLocalizedString::Name name, const WebString& value) {
906 int message_id = ToMessageID(name);
907 if (message_id < 0)
908 return WebString();
909 return ReplaceStringPlaceholders(GetContentClient()->GetLocalizedString(
910 message_id), value, NULL);
913 WebString BlinkPlatformImpl::queryLocalizedString(
914 WebLocalizedString::Name name,
915 const WebString& value1,
916 const WebString& value2) {
917 int message_id = ToMessageID(name);
918 if (message_id < 0)
919 return WebString();
920 std::vector<base::string16> values;
921 values.reserve(2);
922 values.push_back(value1);
923 values.push_back(value2);
924 return ReplaceStringPlaceholders(
925 GetContentClient()->GetLocalizedString(message_id), values, NULL);
928 double BlinkPlatformImpl::currentTime() {
929 return base::Time::Now().ToDoubleT();
932 double BlinkPlatformImpl::monotonicallyIncreasingTime() {
933 return base::TimeTicks::Now().ToInternalValue() /
934 static_cast<double>(base::Time::kMicrosecondsPerSecond);
937 void BlinkPlatformImpl::cryptographicallyRandomValues(
938 unsigned char* buffer, size_t length) {
939 base::RandBytes(buffer, length);
942 void BlinkPlatformImpl::setSharedTimerFiredFunction(void (*func)()) {
943 shared_timer_func_ = func;
946 void BlinkPlatformImpl::setSharedTimerFireInterval(
947 double interval_seconds) {
948 shared_timer_fire_time_ = interval_seconds + monotonicallyIncreasingTime();
949 if (shared_timer_suspended_) {
950 shared_timer_fire_time_was_set_while_suspended_ = true;
951 return;
954 // By converting between double and int64 representation, we run the risk
955 // of losing precision due to rounding errors. Performing computations in
956 // microseconds reduces this risk somewhat. But there still is the potential
957 // of us computing a fire time for the timer that is shorter than what we
958 // need.
959 // As the event loop will check event deadlines prior to actually firing
960 // them, there is a risk of needlessly rescheduling events and of
961 // needlessly looping if sleep times are too short even by small amounts.
962 // This results in measurable performance degradation unless we use ceil() to
963 // always round up the sleep times.
964 int64 interval = static_cast<int64>(
965 ceil(interval_seconds * base::Time::kMillisecondsPerSecond)
966 * base::Time::kMicrosecondsPerMillisecond);
968 if (interval < 0)
969 interval = 0;
971 shared_timer_.Stop();
972 shared_timer_.Start(FROM_HERE, base::TimeDelta::FromMicroseconds(interval),
973 this, &BlinkPlatformImpl::DoTimeout);
974 OnStartSharedTimer(base::TimeDelta::FromMicroseconds(interval));
977 void BlinkPlatformImpl::stopSharedTimer() {
978 shared_timer_.Stop();
981 void BlinkPlatformImpl::callOnMainThread(
982 void (*func)(void*), void* context) {
983 main_loop_->PostTask(FROM_HERE, base::Bind(func, context));
986 blink::WebGestureCurve* BlinkPlatformImpl::createFlingAnimationCurve(
987 blink::WebGestureDevice device_source,
988 const blink::WebFloatPoint& velocity,
989 const blink::WebSize& cumulative_scroll) {
990 #if defined(OS_ANDROID)
991 return FlingAnimatorImpl::CreateAndroidGestureCurve(
992 velocity,
993 cumulative_scroll);
994 #endif
996 if (device_source == blink::WebGestureDeviceTouchscreen)
997 return fling_curve_configuration_->CreateForTouchScreen(velocity,
998 cumulative_scroll);
1000 return fling_curve_configuration_->CreateForTouchPad(velocity,
1001 cumulative_scroll);
1004 void BlinkPlatformImpl::didStartWorkerRunLoop(
1005 const blink::WebWorkerRunLoop& runLoop) {
1006 WorkerTaskRunner* worker_task_runner = WorkerTaskRunner::Instance();
1007 worker_task_runner->OnWorkerRunLoopStarted(runLoop);
1010 void BlinkPlatformImpl::didStopWorkerRunLoop(
1011 const blink::WebWorkerRunLoop& runLoop) {
1012 WorkerTaskRunner* worker_task_runner = WorkerTaskRunner::Instance();
1013 worker_task_runner->OnWorkerRunLoopStopped(runLoop);
1016 blink::WebCrypto* BlinkPlatformImpl::crypto() {
1017 return &web_crypto_;
1021 WebThemeEngine* BlinkPlatformImpl::themeEngine() {
1022 return &native_theme_engine_;
1025 WebFallbackThemeEngine* BlinkPlatformImpl::fallbackThemeEngine() {
1026 return &fallback_theme_engine_;
1029 blink::Platform::FileHandle BlinkPlatformImpl::databaseOpenFile(
1030 const blink::WebString& vfs_file_name, int desired_flags) {
1031 #if defined(OS_WIN)
1032 return INVALID_HANDLE_VALUE;
1033 #elif defined(OS_POSIX)
1034 return -1;
1035 #endif
1038 int BlinkPlatformImpl::databaseDeleteFile(
1039 const blink::WebString& vfs_file_name, bool sync_dir) {
1040 return -1;
1043 long BlinkPlatformImpl::databaseGetFileAttributes(
1044 const blink::WebString& vfs_file_name) {
1045 return 0;
1048 long long BlinkPlatformImpl::databaseGetFileSize(
1049 const blink::WebString& vfs_file_name) {
1050 return 0;
1053 long long BlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
1054 const blink::WebString& origin_identifier) {
1055 return 0;
1058 blink::WebString BlinkPlatformImpl::signedPublicKeyAndChallengeString(
1059 unsigned key_size_index,
1060 const blink::WebString& challenge,
1061 const blink::WebURL& url) {
1062 return blink::WebString("");
1065 static scoped_ptr<base::ProcessMetrics> CurrentProcessMetrics() {
1066 using base::ProcessMetrics;
1067 #if defined(OS_MACOSX)
1068 return scoped_ptr<ProcessMetrics>(
1069 // The default port provider is sufficient to get data for the current
1070 // process.
1071 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle(),
1072 NULL));
1073 #else
1074 return scoped_ptr<ProcessMetrics>(
1075 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle()));
1076 #endif
1079 static size_t getMemoryUsageMB(bool bypass_cache) {
1080 size_t current_mem_usage = 0;
1081 MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::GetInstance();
1082 if (!bypass_cache &&
1083 mem_usage_cache_singleton->IsCachedValueValid(&current_mem_usage))
1084 return current_mem_usage;
1086 current_mem_usage = GetMemoryUsageKB() >> 10;
1087 mem_usage_cache_singleton->SetMemoryValue(current_mem_usage);
1088 return current_mem_usage;
1091 size_t BlinkPlatformImpl::memoryUsageMB() {
1092 return getMemoryUsageMB(false);
1095 size_t BlinkPlatformImpl::actualMemoryUsageMB() {
1096 return getMemoryUsageMB(true);
1099 size_t BlinkPlatformImpl::physicalMemoryMB() {
1100 return static_cast<size_t>(base::SysInfo::AmountOfPhysicalMemoryMB());
1103 size_t BlinkPlatformImpl::virtualMemoryLimitMB() {
1104 return static_cast<size_t>(base::SysInfo::AmountOfVirtualMemoryMB());
1107 size_t BlinkPlatformImpl::numberOfProcessors() {
1108 return static_cast<size_t>(base::SysInfo::NumberOfProcessors());
1111 void BlinkPlatformImpl::startHeapProfiling(
1112 const blink::WebString& prefix) {
1113 // FIXME(morrita): Make this built on windows.
1114 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1115 HeapProfilerStart(prefix.utf8().data());
1116 #endif
1119 void BlinkPlatformImpl::stopHeapProfiling() {
1120 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1121 HeapProfilerStop();
1122 #endif
1125 void BlinkPlatformImpl::dumpHeapProfiling(
1126 const blink::WebString& reason) {
1127 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1128 HeapProfilerDump(reason.utf8().data());
1129 #endif
1132 WebString BlinkPlatformImpl::getHeapProfile() {
1133 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1134 char* data = GetHeapProfile();
1135 WebString result = WebString::fromUTF8(std::string(data));
1136 free(data);
1137 return result;
1138 #else
1139 return WebString();
1140 #endif
1143 bool BlinkPlatformImpl::processMemorySizesInBytes(
1144 size_t* private_bytes,
1145 size_t* shared_bytes) {
1146 return CurrentProcessMetrics()->GetMemoryBytes(private_bytes, shared_bytes);
1149 bool BlinkPlatformImpl::memoryAllocatorWasteInBytes(size_t* size) {
1150 return base::allocator::GetAllocatorWasteSize(size);
1153 blink::WebDiscardableMemory*
1154 BlinkPlatformImpl::allocateAndLockDiscardableMemory(size_t bytes) {
1155 base::DiscardableMemoryType type =
1156 base::DiscardableMemory::GetPreferredType();
1157 if (type == base::DISCARDABLE_MEMORY_TYPE_EMULATED)
1158 return NULL;
1159 return content::WebDiscardableMemoryImpl::CreateLockedMemory(bytes).release();
1162 size_t BlinkPlatformImpl::maxDecodedImageBytes() {
1163 #if defined(OS_ANDROID)
1164 if (base::SysInfo::IsLowEndDevice()) {
1165 // Limit image decoded size to 3M pixels on low end devices.
1166 // 4 is maximum number of bytes per pixel.
1167 return 3 * 1024 * 1024 * 4;
1169 // For other devices, limit decoded image size based on the amount of physical
1170 // memory.
1171 // In some cases all physical memory is not accessible by Chromium, as it can
1172 // be reserved for direct use by certain hardware. Thus, we set the limit so
1173 // that 1.6GB of reported physical memory on a 2GB device is enough to set the
1174 // limit at 16M pixels, which is a desirable value since 4K*4K is a relatively
1175 // common texture size.
1176 return base::SysInfo::AmountOfPhysicalMemory() / 25;
1177 #else
1178 return noDecodedImageByteLimit;
1179 #endif
1182 void BlinkPlatformImpl::SetFlingCurveParameters(
1183 const std::vector<float>& new_touchpad,
1184 const std::vector<float>& new_touchscreen) {
1185 fling_curve_configuration_->SetCurveParameters(new_touchpad, new_touchscreen);
1188 void BlinkPlatformImpl::SuspendSharedTimer() {
1189 ++shared_timer_suspended_;
1192 void BlinkPlatformImpl::ResumeSharedTimer() {
1193 DCHECK_GT(shared_timer_suspended_, 0);
1195 // The shared timer may have fired or been adjusted while we were suspended.
1196 if (--shared_timer_suspended_ == 0 &&
1197 (!shared_timer_.IsRunning() ||
1198 shared_timer_fire_time_was_set_while_suspended_)) {
1199 shared_timer_fire_time_was_set_while_suspended_ = false;
1200 setSharedTimerFireInterval(
1201 shared_timer_fire_time_ - monotonicallyIncreasingTime());
1205 // static
1206 void BlinkPlatformImpl::DestroyCurrentThread(void* thread) {
1207 WebThreadImplForMessageLoop* impl =
1208 static_cast<WebThreadImplForMessageLoop*>(thread);
1209 delete impl;
1212 } // namespace content