Count All Cards for Explanatory Link Support
[chromium-blink-merge.git] / webkit / child / webkitplatformsupport_impl.cc
bloba599fa57fe9ea4377cd09472200b7cd94ee0ec99
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "webkit/child/webkitplatformsupport_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/platform_file.h"
21 #include "base/process/process_metrics.h"
22 #include "base/rand_util.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/synchronization/lock.h"
27 #include "base/sys_info.h"
28 #include "base/time/time.h"
29 #include "grit/blink_resources.h"
30 #include "grit/webkit_resources.h"
31 #include "grit/webkit_strings.h"
32 #include "net/base/data_url.h"
33 #include "net/base/mime_util.h"
34 #include "net/base/net_errors.h"
35 #include "third_party/WebKit/public/platform/WebCookie.h"
36 #include "third_party/WebKit/public/platform/WebData.h"
37 #include "third_party/WebKit/public/platform/WebDiscardableMemory.h"
38 #include "third_party/WebKit/public/platform/WebGestureCurve.h"
39 #include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
40 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
41 #include "third_party/WebKit/public/platform/WebString.h"
42 #include "third_party/WebKit/public/platform/WebURL.h"
43 #include "third_party/WebKit/public/platform/WebVector.h"
44 #include "third_party/WebKit/public/web/WebFrameClient.h"
45 #include "third_party/WebKit/public/web/WebInputEvent.h"
46 #include "ui/base/layout.h"
47 #include "webkit/child/webkit_child_helpers.h"
48 #include "webkit/child/websocketstreamhandle_impl.h"
49 #include "webkit/child/weburlloader_impl.h"
50 #include "webkit/common/user_agent/user_agent.h"
52 #if defined(OS_ANDROID)
53 #include "base/android/sys_utils.h"
54 #endif
56 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
57 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
58 #endif
60 using blink::WebAudioBus;
61 using blink::WebCookie;
62 using blink::WebData;
63 using blink::WebLocalizedString;
64 using blink::WebPluginListBuilder;
65 using blink::WebString;
66 using blink::WebSocketStreamHandle;
67 using blink::WebURL;
68 using blink::WebURLError;
69 using blink::WebURLLoader;
70 using blink::WebVector;
72 namespace {
74 // A simple class to cache the memory usage for a given amount of time.
75 class MemoryUsageCache {
76 public:
77 // Retrieves the Singleton.
78 static MemoryUsageCache* GetInstance() {
79 return Singleton<MemoryUsageCache>::get();
82 MemoryUsageCache() : memory_value_(0) { Init(); }
83 ~MemoryUsageCache() {}
85 void Init() {
86 const unsigned int kCacheSeconds = 1;
87 cache_valid_time_ = base::TimeDelta::FromSeconds(kCacheSeconds);
90 // Returns true if the cached value is fresh.
91 // Returns false if the cached value is stale, or if |cached_value| is NULL.
92 bool IsCachedValueValid(size_t* cached_value) {
93 base::AutoLock scoped_lock(lock_);
94 if (!cached_value)
95 return false;
96 if (base::Time::Now() - last_updated_time_ > cache_valid_time_)
97 return false;
98 *cached_value = memory_value_;
99 return true;
102 // Setter for |memory_value_|, refreshes |last_updated_time_|.
103 void SetMemoryValue(const size_t value) {
104 base::AutoLock scoped_lock(lock_);
105 memory_value_ = value;
106 last_updated_time_ = base::Time::Now();
109 private:
110 // The cached memory value.
111 size_t memory_value_;
113 // How long the cached value should remain valid.
114 base::TimeDelta cache_valid_time_;
116 // The last time the cached value was updated.
117 base::Time last_updated_time_;
119 base::Lock lock_;
122 } // anonymous namespace
124 namespace webkit_glue {
126 static int ToMessageID(WebLocalizedString::Name name) {
127 switch (name) {
128 case WebLocalizedString::AXAMPMFieldText:
129 return IDS_AX_AM_PM_FIELD_TEXT;
130 case WebLocalizedString::AXButtonActionVerb:
131 return IDS_AX_BUTTON_ACTION_VERB;
132 case WebLocalizedString::AXCheckedCheckBoxActionVerb:
133 return IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB;
134 case WebLocalizedString::AXDateTimeFieldEmptyValueText:
135 return IDS_AX_DATE_TIME_FIELD_EMPTY_VALUE_TEXT;
136 case WebLocalizedString::AXDayOfMonthFieldText:
137 return IDS_AX_DAY_OF_MONTH_FIELD_TEXT;
138 case WebLocalizedString::AXHeadingText:
139 return IDS_AX_ROLE_HEADING;
140 case WebLocalizedString::AXHourFieldText:
141 return IDS_AX_HOUR_FIELD_TEXT;
142 case WebLocalizedString::AXImageMapText:
143 return IDS_AX_ROLE_IMAGE_MAP;
144 case WebLocalizedString::AXLinkActionVerb:
145 return IDS_AX_LINK_ACTION_VERB;
146 case WebLocalizedString::AXLinkText:
147 return IDS_AX_ROLE_LINK;
148 case WebLocalizedString::AXListMarkerText:
149 return IDS_AX_ROLE_LIST_MARKER;
150 case WebLocalizedString::AXMediaDefault:
151 return IDS_AX_MEDIA_DEFAULT;
152 case WebLocalizedString::AXMediaAudioElement:
153 return IDS_AX_MEDIA_AUDIO_ELEMENT;
154 case WebLocalizedString::AXMediaVideoElement:
155 return IDS_AX_MEDIA_VIDEO_ELEMENT;
156 case WebLocalizedString::AXMediaMuteButton:
157 return IDS_AX_MEDIA_MUTE_BUTTON;
158 case WebLocalizedString::AXMediaUnMuteButton:
159 return IDS_AX_MEDIA_UNMUTE_BUTTON;
160 case WebLocalizedString::AXMediaPlayButton:
161 return IDS_AX_MEDIA_PLAY_BUTTON;
162 case WebLocalizedString::AXMediaPauseButton:
163 return IDS_AX_MEDIA_PAUSE_BUTTON;
164 case WebLocalizedString::AXMediaSlider:
165 return IDS_AX_MEDIA_SLIDER;
166 case WebLocalizedString::AXMediaSliderThumb:
167 return IDS_AX_MEDIA_SLIDER_THUMB;
168 case WebLocalizedString::AXMediaCurrentTimeDisplay:
169 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY;
170 case WebLocalizedString::AXMediaTimeRemainingDisplay:
171 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY;
172 case WebLocalizedString::AXMediaStatusDisplay:
173 return IDS_AX_MEDIA_STATUS_DISPLAY;
174 case WebLocalizedString::AXMediaEnterFullscreenButton:
175 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON;
176 case WebLocalizedString::AXMediaExitFullscreenButton:
177 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON;
178 case WebLocalizedString::AXMediaShowClosedCaptionsButton:
179 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON;
180 case WebLocalizedString::AXMediaHideClosedCaptionsButton:
181 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON;
182 case WebLocalizedString::AXMediaAudioElementHelp:
183 return IDS_AX_MEDIA_AUDIO_ELEMENT_HELP;
184 case WebLocalizedString::AXMediaVideoElementHelp:
185 return IDS_AX_MEDIA_VIDEO_ELEMENT_HELP;
186 case WebLocalizedString::AXMediaMuteButtonHelp:
187 return IDS_AX_MEDIA_MUTE_BUTTON_HELP;
188 case WebLocalizedString::AXMediaUnMuteButtonHelp:
189 return IDS_AX_MEDIA_UNMUTE_BUTTON_HELP;
190 case WebLocalizedString::AXMediaPlayButtonHelp:
191 return IDS_AX_MEDIA_PLAY_BUTTON_HELP;
192 case WebLocalizedString::AXMediaPauseButtonHelp:
193 return IDS_AX_MEDIA_PAUSE_BUTTON_HELP;
194 case WebLocalizedString::AXMediaSliderHelp:
195 return IDS_AX_MEDIA_SLIDER_HELP;
196 case WebLocalizedString::AXMediaSliderThumbHelp:
197 return IDS_AX_MEDIA_SLIDER_THUMB_HELP;
198 case WebLocalizedString::AXMediaCurrentTimeDisplayHelp:
199 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY_HELP;
200 case WebLocalizedString::AXMediaTimeRemainingDisplayHelp:
201 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY_HELP;
202 case WebLocalizedString::AXMediaStatusDisplayHelp:
203 return IDS_AX_MEDIA_STATUS_DISPLAY_HELP;
204 case WebLocalizedString::AXMediaEnterFullscreenButtonHelp:
205 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON_HELP;
206 case WebLocalizedString::AXMediaExitFullscreenButtonHelp:
207 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON_HELP;
208 case WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp:
209 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON_HELP;
210 case WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp:
211 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON_HELP;
212 case WebLocalizedString::AXMillisecondFieldText:
213 return IDS_AX_MILLISECOND_FIELD_TEXT;
214 case WebLocalizedString::AXMinuteFieldText:
215 return IDS_AX_MINUTE_FIELD_TEXT;
216 case WebLocalizedString::AXMonthFieldText:
217 return IDS_AX_MONTH_FIELD_TEXT;
218 case WebLocalizedString::AXRadioButtonActionVerb:
219 return IDS_AX_RADIO_BUTTON_ACTION_VERB;
220 case WebLocalizedString::AXSecondFieldText:
221 return IDS_AX_SECOND_FIELD_TEXT;
222 case WebLocalizedString::AXTextFieldActionVerb:
223 return IDS_AX_TEXT_FIELD_ACTION_VERB;
224 case WebLocalizedString::AXUncheckedCheckBoxActionVerb:
225 return IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB;
226 case WebLocalizedString::AXWebAreaText:
227 return IDS_AX_ROLE_WEB_AREA;
228 case WebLocalizedString::AXWeekOfYearFieldText:
229 return IDS_AX_WEEK_OF_YEAR_FIELD_TEXT;
230 case WebLocalizedString::AXYearFieldText:
231 return IDS_AX_YEAR_FIELD_TEXT;
232 case WebLocalizedString::CalendarClear:
233 return IDS_FORM_CALENDAR_CLEAR;
234 case WebLocalizedString::CalendarToday:
235 return IDS_FORM_CALENDAR_TODAY;
236 case WebLocalizedString::DateFormatDayInMonthLabel:
237 return IDS_FORM_DATE_FORMAT_DAY_IN_MONTH;
238 case WebLocalizedString::DateFormatMonthLabel:
239 return IDS_FORM_DATE_FORMAT_MONTH;
240 case WebLocalizedString::DateFormatYearLabel:
241 return IDS_FORM_DATE_FORMAT_YEAR;
242 case WebLocalizedString::DetailsLabel:
243 return IDS_DETAILS_WITHOUT_SUMMARY_LABEL;
244 case WebLocalizedString::FileButtonChooseFileLabel:
245 return IDS_FORM_FILE_BUTTON_LABEL;
246 case WebLocalizedString::FileButtonChooseMultipleFilesLabel:
247 return IDS_FORM_MULTIPLE_FILES_BUTTON_LABEL;
248 case WebLocalizedString::FileButtonNoFileSelectedLabel:
249 return IDS_FORM_FILE_NO_FILE_LABEL;
250 case WebLocalizedString::InputElementAltText:
251 return IDS_FORM_INPUT_ALT;
252 case WebLocalizedString::KeygenMenuHighGradeKeySize:
253 return IDS_KEYGEN_HIGH_GRADE_KEY;
254 case WebLocalizedString::KeygenMenuMediumGradeKeySize:
255 return IDS_KEYGEN_MED_GRADE_KEY;
256 case WebLocalizedString::MissingPluginText:
257 return IDS_PLUGIN_INITIALIZATION_ERROR;
258 case WebLocalizedString::MultipleFileUploadText:
259 return IDS_FORM_FILE_MULTIPLE_UPLOAD;
260 case WebLocalizedString::OtherColorLabel:
261 return IDS_FORM_OTHER_COLOR_LABEL;
262 case WebLocalizedString::OtherDateLabel:
263 return IDS_FORM_OTHER_DATE_LABEL;
264 case WebLocalizedString::OtherMonthLabel:
265 return IDS_FORM_OTHER_MONTH_LABEL;
266 case WebLocalizedString::OtherTimeLabel:
267 return IDS_FORM_OTHER_TIME_LABEL;
268 case WebLocalizedString::OtherWeekLabel:
269 return IDS_FORM_OTHER_WEEK_LABEL;
270 case WebLocalizedString::PlaceholderForDayOfMonthField:
271 return IDS_FORM_PLACEHOLDER_FOR_DAY_OF_MONTH_FIELD;
272 case WebLocalizedString::PlaceholderForMonthField:
273 return IDS_FORM_PLACEHOLDER_FOR_MONTH_FIELD;
274 case WebLocalizedString::PlaceholderForYearField:
275 return IDS_FORM_PLACEHOLDER_FOR_YEAR_FIELD;
276 case WebLocalizedString::ResetButtonDefaultLabel:
277 return IDS_FORM_RESET_LABEL;
278 case WebLocalizedString::SearchableIndexIntroduction:
279 return IDS_SEARCHABLE_INDEX_INTRO;
280 case WebLocalizedString::SearchMenuClearRecentSearchesText:
281 return IDS_RECENT_SEARCHES_CLEAR;
282 case WebLocalizedString::SearchMenuNoRecentSearchesText:
283 return IDS_RECENT_SEARCHES_NONE;
284 case WebLocalizedString::SearchMenuRecentSearchesText:
285 return IDS_RECENT_SEARCHES;
286 case WebLocalizedString::SubmitButtonDefaultLabel:
287 return IDS_FORM_SUBMIT_LABEL;
288 case WebLocalizedString::ThisMonthButtonLabel:
289 return IDS_FORM_THIS_MONTH_LABEL;
290 case WebLocalizedString::ThisWeekButtonLabel:
291 return IDS_FORM_THIS_WEEK_LABEL;
292 case WebLocalizedString::ValidationBadInputForDateTime:
293 return IDS_FORM_VALIDATION_BAD_INPUT_DATETIME;
294 case WebLocalizedString::ValidationBadInputForNumber:
295 return IDS_FORM_VALIDATION_BAD_INPUT_NUMBER;
296 case WebLocalizedString::ValidationPatternMismatch:
297 return IDS_FORM_VALIDATION_PATTERN_MISMATCH;
298 case WebLocalizedString::ValidationRangeOverflow:
299 return IDS_FORM_VALIDATION_RANGE_OVERFLOW;
300 case WebLocalizedString::ValidationRangeOverflowDateTime:
301 return IDS_FORM_VALIDATION_RANGE_OVERFLOW_DATETIME;
302 case WebLocalizedString::ValidationRangeUnderflow:
303 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW;
304 case WebLocalizedString::ValidationRangeUnderflowDateTime:
305 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW_DATETIME;
306 case WebLocalizedString::ValidationStepMismatch:
307 return IDS_FORM_VALIDATION_STEP_MISMATCH;
308 case WebLocalizedString::ValidationStepMismatchCloseToLimit:
309 return IDS_FORM_VALIDATION_STEP_MISMATCH_CLOSE_TO_LIMIT;
310 case WebLocalizedString::ValidationTooLong:
311 return IDS_FORM_VALIDATION_TOO_LONG;
312 case WebLocalizedString::ValidationTypeMismatch:
313 return IDS_FORM_VALIDATION_TYPE_MISMATCH;
314 case WebLocalizedString::ValidationTypeMismatchForEmail:
315 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL;
316 case WebLocalizedString::ValidationTypeMismatchForEmailEmpty:
317 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY;
318 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyDomain:
319 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_DOMAIN;
320 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyLocal:
321 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_LOCAL;
322 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDomain:
323 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOMAIN;
324 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots:
325 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOTS;
326 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidLocal:
327 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_LOCAL;
328 case WebLocalizedString::ValidationTypeMismatchForEmailNoAtSign:
329 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_NO_AT_SIGN;
330 case WebLocalizedString::ValidationTypeMismatchForMultipleEmail:
331 return IDS_FORM_VALIDATION_TYPE_MISMATCH_MULTIPLE_EMAIL;
332 case WebLocalizedString::ValidationTypeMismatchForURL:
333 return IDS_FORM_VALIDATION_TYPE_MISMATCH_URL;
334 case WebLocalizedString::ValidationValueMissing:
335 return IDS_FORM_VALIDATION_VALUE_MISSING;
336 case WebLocalizedString::ValidationValueMissingForCheckbox:
337 return IDS_FORM_VALIDATION_VALUE_MISSING_CHECKBOX;
338 case WebLocalizedString::ValidationValueMissingForFile:
339 return IDS_FORM_VALIDATION_VALUE_MISSING_FILE;
340 case WebLocalizedString::ValidationValueMissingForMultipleFile:
341 return IDS_FORM_VALIDATION_VALUE_MISSING_MULTIPLE_FILE;
342 case WebLocalizedString::ValidationValueMissingForRadio:
343 return IDS_FORM_VALIDATION_VALUE_MISSING_RADIO;
344 case WebLocalizedString::ValidationValueMissingForSelect:
345 return IDS_FORM_VALIDATION_VALUE_MISSING_SELECT;
346 case WebLocalizedString::WeekFormatTemplate:
347 return IDS_FORM_INPUT_WEEK_TEMPLATE;
348 case WebLocalizedString::WeekNumberLabel:
349 return IDS_FORM_WEEK_NUMBER_LABEL;
350 // This "default:" line exists to avoid compile warnings about enum
351 // coverage when we add a new symbol to WebLocalizedString.h in WebKit.
352 // After a planned WebKit patch is landed, we need to add a case statement
353 // for the added symbol here.
354 default:
355 break;
357 return -1;
360 WebKitPlatformSupportImpl::WebKitPlatformSupportImpl()
361 : main_loop_(base::MessageLoop::current()),
362 shared_timer_func_(NULL),
363 shared_timer_fire_time_(0.0),
364 shared_timer_fire_time_was_set_while_suspended_(false),
365 shared_timer_suspended_(0) {}
367 WebKitPlatformSupportImpl::~WebKitPlatformSupportImpl() {
370 WebURLLoader* WebKitPlatformSupportImpl::createURLLoader() {
371 return new WebURLLoaderImpl(this);
374 WebSocketStreamHandle* WebKitPlatformSupportImpl::createSocketStreamHandle() {
375 return new WebSocketStreamHandleImpl(this);
378 WebString WebKitPlatformSupportImpl::userAgent(const WebURL& url) {
379 return WebString::fromUTF8(webkit_glue::GetUserAgent(url));
382 WebData WebKitPlatformSupportImpl::parseDataURL(
383 const WebURL& url,
384 WebString& mimetype_out,
385 WebString& charset_out) {
386 std::string mime_type, char_set, data;
387 if (net::DataURL::Parse(url, &mime_type, &char_set, &data)
388 && net::IsSupportedMimeType(mime_type)) {
389 mimetype_out = WebString::fromUTF8(mime_type);
390 charset_out = WebString::fromUTF8(char_set);
391 return data;
393 return WebData();
396 WebURLError WebKitPlatformSupportImpl::cancelledError(
397 const WebURL& unreachableURL) const {
398 return WebURLLoaderImpl::CreateError(unreachableURL, false, net::ERR_ABORTED);
401 void WebKitPlatformSupportImpl::decrementStatsCounter(const char* name) {
402 base::StatsCounter(name).Decrement();
405 void WebKitPlatformSupportImpl::incrementStatsCounter(const char* name) {
406 base::StatsCounter(name).Increment();
409 void WebKitPlatformSupportImpl::histogramCustomCounts(
410 const char* name, int sample, int min, int max, int bucket_count) {
411 // Copied from histogram macro, but without the static variable caching
412 // the histogram because name is dynamic.
413 base::HistogramBase* counter =
414 base::Histogram::FactoryGet(name, min, max, bucket_count,
415 base::HistogramBase::kUmaTargetedHistogramFlag);
416 DCHECK_EQ(name, counter->histogram_name());
417 counter->Add(sample);
420 void WebKitPlatformSupportImpl::histogramEnumeration(
421 const char* name, int sample, int boundary_value) {
422 // Copied from histogram macro, but without the static variable caching
423 // the histogram because name is dynamic.
424 base::HistogramBase* counter =
425 base::LinearHistogram::FactoryGet(name, 1, boundary_value,
426 boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
427 DCHECK_EQ(name, counter->histogram_name());
428 counter->Add(sample);
431 void WebKitPlatformSupportImpl::histogramSparse(const char* name, int sample) {
432 // For sparse histograms, we can use the macro, as it does not incorporate a
433 // static.
434 UMA_HISTOGRAM_SPARSE_SLOWLY(name, sample);
437 const unsigned char* WebKitPlatformSupportImpl::getTraceCategoryEnabledFlag(
438 const char* category_group) {
439 return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(category_group);
442 long* WebKitPlatformSupportImpl::getTraceSamplingState(
443 const unsigned thread_bucket) {
444 switch (thread_bucket) {
445 case 0:
446 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(0));
447 case 1:
448 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(1));
449 case 2:
450 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(2));
451 default:
452 NOTREACHED() << "Unknown thread bucket type.";
454 return NULL;
457 COMPILE_ASSERT(
458 sizeof(blink::Platform::TraceEventHandle) ==
459 sizeof(base::debug::TraceEventHandle),
460 TraceEventHandle_types_must_be_same_size);
462 blink::Platform::TraceEventHandle WebKitPlatformSupportImpl::addTraceEvent(
463 char phase,
464 const unsigned char* category_group_enabled,
465 const char* name,
466 unsigned long long id,
467 int num_args,
468 const char** arg_names,
469 const unsigned char* arg_types,
470 const unsigned long long* arg_values,
471 unsigned char flags) {
472 base::debug::TraceEventHandle handle = TRACE_EVENT_API_ADD_TRACE_EVENT(
473 phase, category_group_enabled, name, id,
474 num_args, arg_names, arg_types, arg_values, NULL, flags);
475 blink::Platform::TraceEventHandle result;
476 memcpy(&result, &handle, sizeof(result));
477 return result;
480 void WebKitPlatformSupportImpl::updateTraceEventDuration(
481 const unsigned char* category_group_enabled,
482 const char* name,
483 TraceEventHandle handle) {
484 base::debug::TraceEventHandle traceEventHandle;
485 memcpy(&traceEventHandle, &handle, sizeof(handle));
486 TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(
487 category_group_enabled, name, traceEventHandle);
490 namespace {
492 WebData loadAudioSpatializationResource(WebKitPlatformSupportImpl* platform,
493 const char* name) {
494 #ifdef IDR_AUDIO_SPATIALIZATION_COMPOSITE
495 if (!strcmp(name, "Composite")) {
496 base::StringPiece resource =
497 platform->GetDataResource(IDR_AUDIO_SPATIALIZATION_COMPOSITE,
498 ui::SCALE_FACTOR_NONE);
499 return WebData(resource.data(), resource.size());
501 #endif
503 #ifdef IDR_AUDIO_SPATIALIZATION_T000_P000
504 const size_t kExpectedSpatializationNameLength = 31;
505 if (strlen(name) != kExpectedSpatializationNameLength) {
506 return WebData();
509 // Extract the azimuth and elevation from the resource name.
510 int azimuth = 0;
511 int elevation = 0;
512 int values_parsed =
513 sscanf(name, "IRC_Composite_C_R0195_T%3d_P%3d", &azimuth, &elevation);
514 if (values_parsed != 2) {
515 return WebData();
518 // The resource index values go through the elevations first, then azimuths.
519 const int kAngleSpacing = 15;
521 // 0 <= elevation <= 90 (or 315 <= elevation <= 345)
522 // in increments of 15 degrees.
523 int elevation_index =
524 elevation <= 90 ? elevation / kAngleSpacing :
525 7 + (elevation - 315) / kAngleSpacing;
526 bool is_elevation_index_good = 0 <= elevation_index && elevation_index < 10;
528 // 0 <= azimuth < 360 in increments of 15 degrees.
529 int azimuth_index = azimuth / kAngleSpacing;
530 bool is_azimuth_index_good = 0 <= azimuth_index && azimuth_index < 24;
532 const int kNumberOfElevations = 10;
533 const int kNumberOfAudioResources = 240;
534 int resource_index = kNumberOfElevations * azimuth_index + elevation_index;
535 bool is_resource_index_good = 0 <= resource_index &&
536 resource_index < kNumberOfAudioResources;
538 if (is_azimuth_index_good && is_elevation_index_good &&
539 is_resource_index_good) {
540 const int kFirstAudioResourceIndex = IDR_AUDIO_SPATIALIZATION_T000_P000;
541 base::StringPiece resource =
542 platform->GetDataResource(kFirstAudioResourceIndex + resource_index,
543 ui::SCALE_FACTOR_NONE);
544 return WebData(resource.data(), resource.size());
546 #endif // IDR_AUDIO_SPATIALIZATION_T000_P000
548 NOTREACHED();
549 return WebData();
552 struct DataResource {
553 const char* name;
554 int id;
555 ui::ScaleFactor scale_factor;
558 const DataResource kDataResources[] = {
559 { "missingImage", IDR_BROKENIMAGE, ui::SCALE_FACTOR_100P },
560 { "missingImage@2x", IDR_BROKENIMAGE, ui::SCALE_FACTOR_200P },
561 { "mediaplayerPause", IDR_MEDIAPLAYER_PAUSE_BUTTON, ui::SCALE_FACTOR_100P },
562 { "mediaplayerPauseHover",
563 IDR_MEDIAPLAYER_PAUSE_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
564 { "mediaplayerPauseDown",
565 IDR_MEDIAPLAYER_PAUSE_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
566 { "mediaplayerPlay", IDR_MEDIAPLAYER_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
567 { "mediaplayerPlayHover",
568 IDR_MEDIAPLAYER_PLAY_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
569 { "mediaplayerPlayDown",
570 IDR_MEDIAPLAYER_PLAY_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
571 { "mediaplayerPlayDisabled",
572 IDR_MEDIAPLAYER_PLAY_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
573 { "mediaplayerSoundLevel3",
574 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON, ui::SCALE_FACTOR_100P },
575 { "mediaplayerSoundLevel3Hover",
576 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
577 { "mediaplayerSoundLevel3Down",
578 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
579 { "mediaplayerSoundLevel2",
580 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON, ui::SCALE_FACTOR_100P },
581 { "mediaplayerSoundLevel2Hover",
582 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
583 { "mediaplayerSoundLevel2Down",
584 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
585 { "mediaplayerSoundLevel1",
586 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON, ui::SCALE_FACTOR_100P },
587 { "mediaplayerSoundLevel1Hover",
588 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
589 { "mediaplayerSoundLevel1Down",
590 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
591 { "mediaplayerSoundLevel0",
592 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON, ui::SCALE_FACTOR_100P },
593 { "mediaplayerSoundLevel0Hover",
594 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
595 { "mediaplayerSoundLevel0Down",
596 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
597 { "mediaplayerSoundDisabled",
598 IDR_MEDIAPLAYER_SOUND_DISABLED, ui::SCALE_FACTOR_100P },
599 { "mediaplayerSliderThumb",
600 IDR_MEDIAPLAYER_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
601 { "mediaplayerSliderThumbHover",
602 IDR_MEDIAPLAYER_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
603 { "mediaplayerSliderThumbDown",
604 IDR_MEDIAPLAYER_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
605 { "mediaplayerVolumeSliderThumb",
606 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
607 { "mediaplayerVolumeSliderThumbHover",
608 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
609 { "mediaplayerVolumeSliderThumbDown",
610 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
611 { "mediaplayerVolumeSliderThumbDisabled",
612 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DISABLED, ui::SCALE_FACTOR_100P },
613 { "mediaplayerClosedCaption",
614 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON, ui::SCALE_FACTOR_100P },
615 { "mediaplayerClosedCaptionHover",
616 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
617 { "mediaplayerClosedCaptionDown",
618 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
619 { "mediaplayerClosedCaptionDisabled",
620 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
621 { "mediaplayerFullscreen",
622 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON, ui::SCALE_FACTOR_100P },
623 { "mediaplayerFullscreenHover",
624 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
625 { "mediaplayerFullscreenDown",
626 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
627 { "mediaplayerFullscreenDisabled",
628 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
629 #if defined(OS_ANDROID)
630 { "mediaplayerOverlayPlay",
631 IDR_MEDIAPLAYER_OVERLAY_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
632 #endif
633 #if defined(OS_MACOSX)
634 { "overhangPattern", IDR_OVERHANG_PATTERN, ui::SCALE_FACTOR_100P },
635 { "overhangShadow", IDR_OVERHANG_SHADOW, ui::SCALE_FACTOR_100P },
636 #endif
637 { "panIcon", IDR_PAN_SCROLL_ICON, ui::SCALE_FACTOR_100P },
638 { "searchCancel", IDR_SEARCH_CANCEL, ui::SCALE_FACTOR_100P },
639 { "searchCancelPressed", IDR_SEARCH_CANCEL_PRESSED, ui::SCALE_FACTOR_100P },
640 { "searchMagnifier", IDR_SEARCH_MAGNIFIER, ui::SCALE_FACTOR_100P },
641 { "searchMagnifierResults",
642 IDR_SEARCH_MAGNIFIER_RESULTS, ui::SCALE_FACTOR_100P },
643 { "textAreaResizeCorner", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_100P },
644 { "textAreaResizeCorner@2x", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_200P },
645 { "inputSpeech", IDR_INPUT_SPEECH, ui::SCALE_FACTOR_100P },
646 { "inputSpeechRecording", IDR_INPUT_SPEECH_RECORDING, ui::SCALE_FACTOR_100P },
647 { "inputSpeechWaiting", IDR_INPUT_SPEECH_WAITING, ui::SCALE_FACTOR_100P },
648 { "americanExpressCC", IDR_AUTOFILL_CC_AMEX, ui::SCALE_FACTOR_100P },
649 { "dinersCC", IDR_AUTOFILL_CC_DINERS, ui::SCALE_FACTOR_100P },
650 { "discoverCC", IDR_AUTOFILL_CC_DISCOVER, ui::SCALE_FACTOR_100P },
651 { "genericCC", IDR_AUTOFILL_CC_GENERIC, ui::SCALE_FACTOR_100P },
652 { "jcbCC", IDR_AUTOFILL_CC_JCB, ui::SCALE_FACTOR_100P },
653 { "masterCardCC", IDR_AUTOFILL_CC_MASTERCARD, ui::SCALE_FACTOR_100P },
654 { "visaCC", IDR_AUTOFILL_CC_VISA, ui::SCALE_FACTOR_100P },
655 { "generatePassword", IDR_PASSWORD_GENERATION_ICON, ui::SCALE_FACTOR_100P },
656 { "generatePasswordHover",
657 IDR_PASSWORD_GENERATION_ICON_HOVER, ui::SCALE_FACTOR_100P },
658 { "syntheticTouchCursor",
659 IDR_SYNTHETIC_TOUCH_CURSOR, ui::SCALE_FACTOR_100P },
662 } // namespace
664 WebData WebKitPlatformSupportImpl::loadResource(const char* name) {
665 // Some clients will call into this method with an empty |name| when they have
666 // optional resources. For example, the PopupMenuChromium code can have icons
667 // for some Autofill items but not for others.
668 if (!strlen(name))
669 return WebData();
671 // Check the name prefix to see if it's an audio resource.
672 if (StartsWithASCII(name, "IRC_Composite", true) ||
673 StartsWithASCII(name, "Composite", true))
674 return loadAudioSpatializationResource(this, name);
676 // TODO(flackr): We should use a better than linear search here, a trie would
677 // be ideal.
678 for (size_t i = 0; i < arraysize(kDataResources); ++i) {
679 if (!strcmp(name, kDataResources[i].name)) {
680 base::StringPiece resource =
681 GetDataResource(kDataResources[i].id,
682 kDataResources[i].scale_factor);
683 return WebData(resource.data(), resource.size());
687 NOTREACHED() << "Unknown image resource " << name;
688 return WebData();
691 WebString WebKitPlatformSupportImpl::queryLocalizedString(
692 WebLocalizedString::Name name) {
693 int message_id = ToMessageID(name);
694 if (message_id < 0)
695 return WebString();
696 return GetLocalizedString(message_id);
699 WebString WebKitPlatformSupportImpl::queryLocalizedString(
700 WebLocalizedString::Name name, int numeric_value) {
701 return queryLocalizedString(name, base::IntToString16(numeric_value));
704 WebString WebKitPlatformSupportImpl::queryLocalizedString(
705 WebLocalizedString::Name name, const WebString& value) {
706 int message_id = ToMessageID(name);
707 if (message_id < 0)
708 return WebString();
709 return ReplaceStringPlaceholders(GetLocalizedString(message_id), value, NULL);
712 WebString WebKitPlatformSupportImpl::queryLocalizedString(
713 WebLocalizedString::Name name,
714 const WebString& value1,
715 const WebString& value2) {
716 int message_id = ToMessageID(name);
717 if (message_id < 0)
718 return WebString();
719 std::vector<base::string16> values;
720 values.reserve(2);
721 values.push_back(value1);
722 values.push_back(value2);
723 return ReplaceStringPlaceholders(
724 GetLocalizedString(message_id), values, NULL);
727 double WebKitPlatformSupportImpl::currentTime() {
728 return base::Time::Now().ToDoubleT();
731 double WebKitPlatformSupportImpl::monotonicallyIncreasingTime() {
732 return base::TimeTicks::Now().ToInternalValue() /
733 static_cast<double>(base::Time::kMicrosecondsPerSecond);
736 void WebKitPlatformSupportImpl::cryptographicallyRandomValues(
737 unsigned char* buffer, size_t length) {
738 base::RandBytes(buffer, length);
741 void WebKitPlatformSupportImpl::setSharedTimerFiredFunction(void (*func)()) {
742 shared_timer_func_ = func;
745 void WebKitPlatformSupportImpl::setSharedTimerFireInterval(
746 double interval_seconds) {
747 shared_timer_fire_time_ = interval_seconds + monotonicallyIncreasingTime();
748 if (shared_timer_suspended_) {
749 shared_timer_fire_time_was_set_while_suspended_ = true;
750 return;
753 // By converting between double and int64 representation, we run the risk
754 // of losing precision due to rounding errors. Performing computations in
755 // microseconds reduces this risk somewhat. But there still is the potential
756 // of us computing a fire time for the timer that is shorter than what we
757 // need.
758 // As the event loop will check event deadlines prior to actually firing
759 // them, there is a risk of needlessly rescheduling events and of
760 // needlessly looping if sleep times are too short even by small amounts.
761 // This results in measurable performance degradation unless we use ceil() to
762 // always round up the sleep times.
763 int64 interval = static_cast<int64>(
764 ceil(interval_seconds * base::Time::kMillisecondsPerSecond)
765 * base::Time::kMicrosecondsPerMillisecond);
767 if (interval < 0)
768 interval = 0;
770 shared_timer_.Stop();
771 shared_timer_.Start(FROM_HERE, base::TimeDelta::FromMicroseconds(interval),
772 this, &WebKitPlatformSupportImpl::DoTimeout);
773 OnStartSharedTimer(base::TimeDelta::FromMicroseconds(interval));
776 void WebKitPlatformSupportImpl::stopSharedTimer() {
777 shared_timer_.Stop();
780 void WebKitPlatformSupportImpl::callOnMainThread(
781 void (*func)(void*), void* context) {
782 main_loop_->PostTask(FROM_HERE, base::Bind(func, context));
785 base::PlatformFile WebKitPlatformSupportImpl::databaseOpenFile(
786 const blink::WebString& vfs_file_name, int desired_flags) {
787 return base::kInvalidPlatformFileValue;
790 int WebKitPlatformSupportImpl::databaseDeleteFile(
791 const blink::WebString& vfs_file_name, bool sync_dir) {
792 return -1;
795 long WebKitPlatformSupportImpl::databaseGetFileAttributes(
796 const blink::WebString& vfs_file_name) {
797 return 0;
800 long long WebKitPlatformSupportImpl::databaseGetFileSize(
801 const blink::WebString& vfs_file_name) {
802 return 0;
805 long long WebKitPlatformSupportImpl::databaseGetSpaceAvailableForOrigin(
806 const blink::WebString& origin_identifier) {
807 return 0;
810 blink::WebString WebKitPlatformSupportImpl::signedPublicKeyAndChallengeString(
811 unsigned key_size_index,
812 const blink::WebString& challenge,
813 const blink::WebURL& url) {
814 return blink::WebString("");
817 static scoped_ptr<base::ProcessMetrics> CurrentProcessMetrics() {
818 using base::ProcessMetrics;
819 #if defined(OS_MACOSX)
820 return scoped_ptr<ProcessMetrics>(
821 // The default port provider is sufficient to get data for the current
822 // process.
823 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle(),
824 NULL));
825 #else
826 return scoped_ptr<ProcessMetrics>(
827 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle()));
828 #endif
831 static size_t getMemoryUsageMB(bool bypass_cache) {
832 size_t current_mem_usage = 0;
833 MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::GetInstance();
834 if (!bypass_cache &&
835 mem_usage_cache_singleton->IsCachedValueValid(&current_mem_usage))
836 return current_mem_usage;
838 current_mem_usage = MemoryUsageKB() >> 10;
839 mem_usage_cache_singleton->SetMemoryValue(current_mem_usage);
840 return current_mem_usage;
843 size_t WebKitPlatformSupportImpl::memoryUsageMB() {
844 return getMemoryUsageMB(false);
847 size_t WebKitPlatformSupportImpl::actualMemoryUsageMB() {
848 return getMemoryUsageMB(true);
851 size_t WebKitPlatformSupportImpl::physicalMemoryMB() {
852 return static_cast<size_t>(base::SysInfo::AmountOfPhysicalMemoryMB());
855 size_t WebKitPlatformSupportImpl::numberOfProcessors() {
856 return static_cast<size_t>(base::SysInfo::NumberOfProcessors());
859 void WebKitPlatformSupportImpl::startHeapProfiling(
860 const blink::WebString& prefix) {
861 // FIXME(morrita): Make this built on windows.
862 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
863 HeapProfilerStart(prefix.utf8().data());
864 #endif
867 void WebKitPlatformSupportImpl::stopHeapProfiling() {
868 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
869 HeapProfilerStop();
870 #endif
873 void WebKitPlatformSupportImpl::dumpHeapProfiling(
874 const blink::WebString& reason) {
875 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
876 HeapProfilerDump(reason.utf8().data());
877 #endif
880 WebString WebKitPlatformSupportImpl::getHeapProfile() {
881 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
882 char* data = GetHeapProfile();
883 WebString result = WebString::fromUTF8(std::string(data));
884 free(data);
885 return result;
886 #else
887 return WebString();
888 #endif
891 bool WebKitPlatformSupportImpl::processMemorySizesInBytes(
892 size_t* private_bytes,
893 size_t* shared_bytes) {
894 return CurrentProcessMetrics()->GetMemoryBytes(private_bytes, shared_bytes);
897 bool WebKitPlatformSupportImpl::memoryAllocatorWasteInBytes(size_t* size) {
898 return base::allocator::GetAllocatorWasteSize(size);
901 size_t WebKitPlatformSupportImpl::maxDecodedImageBytes() {
902 #if defined(OS_ANDROID)
903 if (base::android::SysUtils::IsLowEndDevice()) {
904 // Limit image decoded size to 3M pixels on low end devices.
905 // 4 is maximum number of bytes per pixel.
906 return 3 * 1024 * 1024 * 4;
908 // For other devices, limit decoded image size based on the amount of physical
909 // memory. For a device with 2GB physical memory the limit is 16M pixels.
910 return base::SysInfo::AmountOfPhysicalMemory() / 32;
911 #else
912 return noDecodedImageByteLimit;
913 #endif
916 void WebKitPlatformSupportImpl::SuspendSharedTimer() {
917 ++shared_timer_suspended_;
920 void WebKitPlatformSupportImpl::ResumeSharedTimer() {
921 // The shared timer may have fired or been adjusted while we were suspended.
922 if (--shared_timer_suspended_ == 0 &&
923 (!shared_timer_.IsRunning() ||
924 shared_timer_fire_time_was_set_while_suspended_)) {
925 shared_timer_fire_time_was_set_while_suspended_ = false;
926 setSharedTimerFireInterval(
927 shared_timer_fire_time_ - monotonicallyIncreasingTime());
931 } // namespace webkit_glue