Revert 224458 "Enabling MediaStreamInfoBarTest.DenyingCameraDoes..."
[chromium-blink-merge.git] / webkit / child / webkitplatformsupport_impl.cc
blob44350ce9ae04ea6dd70ab5d2f64034621b1939ec
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/time/time.h"
28 #include "content/public/common/webplugininfo.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/WebString.h"
41 #include "third_party/WebKit/public/platform/WebURL.h"
42 #include "third_party/WebKit/public/platform/WebVector.h"
43 #include "third_party/WebKit/public/web/WebFrameClient.h"
44 #include "third_party/WebKit/public/web/WebInputEvent.h"
45 #include "third_party/WebKit/public/web/WebScreenInfo.h"
46 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
47 #include "ui/base/layout.h"
48 #include "webkit/child/webkit_child_helpers.h"
49 #include "webkit/child/websocketstreamhandle_impl.h"
50 #include "webkit/child/weburlloader_impl.h"
51 #include "webkit/common/user_agent/user_agent.h"
52 #include "webkit/glue/webkit_glue.h"
54 using WebKit::WebAudioBus;
55 using WebKit::WebCookie;
56 using WebKit::WebData;
57 using WebKit::WebLocalizedString;
58 using WebKit::WebPluginListBuilder;
59 using WebKit::WebString;
60 using WebKit::WebSocketStreamHandle;
61 using WebKit::WebURL;
62 using WebKit::WebURLError;
63 using WebKit::WebURLLoader;
64 using WebKit::WebVector;
66 namespace {
68 // A simple class to cache the memory usage for a given amount of time.
69 class MemoryUsageCache {
70 public:
71 // Retrieves the Singleton.
72 static MemoryUsageCache* GetInstance() {
73 return Singleton<MemoryUsageCache>::get();
76 MemoryUsageCache() : memory_value_(0) { Init(); }
77 ~MemoryUsageCache() {}
79 void Init() {
80 const unsigned int kCacheSeconds = 1;
81 cache_valid_time_ = base::TimeDelta::FromSeconds(kCacheSeconds);
84 // Returns true if the cached value is fresh.
85 // Returns false if the cached value is stale, or if |cached_value| is NULL.
86 bool IsCachedValueValid(size_t* cached_value) {
87 base::AutoLock scoped_lock(lock_);
88 if (!cached_value)
89 return false;
90 if (base::Time::Now() - last_updated_time_ > cache_valid_time_)
91 return false;
92 *cached_value = memory_value_;
93 return true;
96 // Setter for |memory_value_|, refreshes |last_updated_time_|.
97 void SetMemoryValue(const size_t value) {
98 base::AutoLock scoped_lock(lock_);
99 memory_value_ = value;
100 last_updated_time_ = base::Time::Now();
103 private:
104 // The cached memory value.
105 size_t memory_value_;
107 // How long the cached value should remain valid.
108 base::TimeDelta cache_valid_time_;
110 // The last time the cached value was updated.
111 base::Time last_updated_time_;
113 base::Lock lock_;
116 } // anonymous namespace
118 namespace webkit_glue {
120 static int ToMessageID(WebLocalizedString::Name name) {
121 switch (name) {
122 case WebLocalizedString::AXAMPMFieldText:
123 return IDS_AX_AM_PM_FIELD_TEXT;
124 case WebLocalizedString::AXButtonActionVerb:
125 return IDS_AX_BUTTON_ACTION_VERB;
126 case WebLocalizedString::AXCheckedCheckBoxActionVerb:
127 return IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB;
128 case WebLocalizedString::AXDateTimeFieldEmptyValueText:
129 return IDS_AX_DATE_TIME_FIELD_EMPTY_VALUE_TEXT;
130 case WebLocalizedString::AXDayOfMonthFieldText:
131 return IDS_AX_DAY_OF_MONTH_FIELD_TEXT;
132 case WebLocalizedString::AXHeadingText:
133 return IDS_AX_ROLE_HEADING;
134 case WebLocalizedString::AXHourFieldText:
135 return IDS_AX_HOUR_FIELD_TEXT;
136 case WebLocalizedString::AXImageMapText:
137 return IDS_AX_ROLE_IMAGE_MAP;
138 case WebLocalizedString::AXLinkActionVerb:
139 return IDS_AX_LINK_ACTION_VERB;
140 case WebLocalizedString::AXLinkText:
141 return IDS_AX_ROLE_LINK;
142 case WebLocalizedString::AXListMarkerText:
143 return IDS_AX_ROLE_LIST_MARKER;
144 case WebLocalizedString::AXMediaDefault:
145 return IDS_AX_MEDIA_DEFAULT;
146 case WebLocalizedString::AXMediaAudioElement:
147 return IDS_AX_MEDIA_AUDIO_ELEMENT;
148 case WebLocalizedString::AXMediaVideoElement:
149 return IDS_AX_MEDIA_VIDEO_ELEMENT;
150 case WebLocalizedString::AXMediaMuteButton:
151 return IDS_AX_MEDIA_MUTE_BUTTON;
152 case WebLocalizedString::AXMediaUnMuteButton:
153 return IDS_AX_MEDIA_UNMUTE_BUTTON;
154 case WebLocalizedString::AXMediaPlayButton:
155 return IDS_AX_MEDIA_PLAY_BUTTON;
156 case WebLocalizedString::AXMediaPauseButton:
157 return IDS_AX_MEDIA_PAUSE_BUTTON;
158 case WebLocalizedString::AXMediaSlider:
159 return IDS_AX_MEDIA_SLIDER;
160 case WebLocalizedString::AXMediaSliderThumb:
161 return IDS_AX_MEDIA_SLIDER_THUMB;
162 case WebLocalizedString::AXMediaRewindButton:
163 return IDS_AX_MEDIA_REWIND_BUTTON;
164 case WebLocalizedString::AXMediaReturnToRealTime:
165 return IDS_AX_MEDIA_RETURN_TO_REALTIME_BUTTON;
166 case WebLocalizedString::AXMediaCurrentTimeDisplay:
167 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY;
168 case WebLocalizedString::AXMediaTimeRemainingDisplay:
169 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY;
170 case WebLocalizedString::AXMediaStatusDisplay:
171 return IDS_AX_MEDIA_STATUS_DISPLAY;
172 case WebLocalizedString::AXMediaEnterFullscreenButton:
173 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON;
174 case WebLocalizedString::AXMediaExitFullscreenButton:
175 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON;
176 case WebLocalizedString::AXMediaSeekForwardButton:
177 return IDS_AX_MEDIA_SEEK_FORWARD_BUTTON;
178 case WebLocalizedString::AXMediaSeekBackButton:
179 return IDS_AX_MEDIA_SEEK_BACK_BUTTON;
180 case WebLocalizedString::AXMediaShowClosedCaptionsButton:
181 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON;
182 case WebLocalizedString::AXMediaHideClosedCaptionsButton:
183 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON;
184 case WebLocalizedString::AXMediaAudioElementHelp:
185 return IDS_AX_MEDIA_AUDIO_ELEMENT_HELP;
186 case WebLocalizedString::AXMediaVideoElementHelp:
187 return IDS_AX_MEDIA_VIDEO_ELEMENT_HELP;
188 case WebLocalizedString::AXMediaMuteButtonHelp:
189 return IDS_AX_MEDIA_MUTE_BUTTON_HELP;
190 case WebLocalizedString::AXMediaUnMuteButtonHelp:
191 return IDS_AX_MEDIA_UNMUTE_BUTTON_HELP;
192 case WebLocalizedString::AXMediaPlayButtonHelp:
193 return IDS_AX_MEDIA_PLAY_BUTTON_HELP;
194 case WebLocalizedString::AXMediaPauseButtonHelp:
195 return IDS_AX_MEDIA_PAUSE_BUTTON_HELP;
196 case WebLocalizedString::AXMediaSliderHelp:
197 return IDS_AX_MEDIA_SLIDER_HELP;
198 case WebLocalizedString::AXMediaSliderThumbHelp:
199 return IDS_AX_MEDIA_SLIDER_THUMB_HELP;
200 case WebLocalizedString::AXMediaRewindButtonHelp:
201 return IDS_AX_MEDIA_REWIND_BUTTON_HELP;
202 case WebLocalizedString::AXMediaReturnToRealTimeHelp:
203 return IDS_AX_MEDIA_RETURN_TO_REALTIME_BUTTON_HELP;
204 case WebLocalizedString::AXMediaCurrentTimeDisplayHelp:
205 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY_HELP;
206 case WebLocalizedString::AXMediaTimeRemainingDisplayHelp:
207 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY_HELP;
208 case WebLocalizedString::AXMediaStatusDisplayHelp:
209 return IDS_AX_MEDIA_STATUS_DISPLAY_HELP;
210 case WebLocalizedString::AXMediaEnterFullscreenButtonHelp:
211 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON_HELP;
212 case WebLocalizedString::AXMediaExitFullscreenButtonHelp:
213 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON_HELP;
214 case WebLocalizedString::AXMediaSeekForwardButtonHelp:
215 return IDS_AX_MEDIA_SEEK_FORWARD_BUTTON_HELP;
216 case WebLocalizedString::AXMediaSeekBackButtonHelp:
217 return IDS_AX_MEDIA_SEEK_BACK_BUTTON_HELP;
218 case WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp:
219 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON_HELP;
220 case WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp:
221 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON_HELP;
222 case WebLocalizedString::AXMillisecondFieldText:
223 return IDS_AX_MILLISECOND_FIELD_TEXT;
224 case WebLocalizedString::AXMinuteFieldText:
225 return IDS_AX_MINUTE_FIELD_TEXT;
226 case WebLocalizedString::AXMonthFieldText:
227 return IDS_AX_MONTH_FIELD_TEXT;
228 case WebLocalizedString::AXRadioButtonActionVerb:
229 return IDS_AX_RADIO_BUTTON_ACTION_VERB;
230 case WebLocalizedString::AXSecondFieldText:
231 return IDS_AX_SECOND_FIELD_TEXT;
232 case WebLocalizedString::AXTextFieldActionVerb:
233 return IDS_AX_TEXT_FIELD_ACTION_VERB;
234 case WebLocalizedString::AXUncheckedCheckBoxActionVerb:
235 return IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB;
236 case WebLocalizedString::AXWebAreaText:
237 return IDS_AX_ROLE_WEB_AREA;
238 case WebLocalizedString::AXWeekOfYearFieldText:
239 return IDS_AX_WEEK_OF_YEAR_FIELD_TEXT;
240 case WebLocalizedString::AXYearFieldText:
241 return IDS_AX_YEAR_FIELD_TEXT;
242 case WebLocalizedString::CalendarClear:
243 return IDS_FORM_CALENDAR_CLEAR;
244 case WebLocalizedString::CalendarToday:
245 return IDS_FORM_CALENDAR_TODAY;
246 case WebLocalizedString::DateFormatDayInMonthLabel:
247 return IDS_FORM_DATE_FORMAT_DAY_IN_MONTH;
248 case WebLocalizedString::DateFormatMonthLabel:
249 return IDS_FORM_DATE_FORMAT_MONTH;
250 case WebLocalizedString::DateFormatYearLabel:
251 return IDS_FORM_DATE_FORMAT_YEAR;
252 case WebLocalizedString::DetailsLabel:
253 return IDS_DETAILS_WITHOUT_SUMMARY_LABEL;
254 case WebLocalizedString::FileButtonChooseFileLabel:
255 return IDS_FORM_FILE_BUTTON_LABEL;
256 case WebLocalizedString::FileButtonChooseMultipleFilesLabel:
257 return IDS_FORM_MULTIPLE_FILES_BUTTON_LABEL;
258 case WebLocalizedString::FileButtonNoFileSelectedLabel:
259 return IDS_FORM_FILE_NO_FILE_LABEL;
260 case WebLocalizedString::InputElementAltText:
261 return IDS_FORM_INPUT_ALT;
262 case WebLocalizedString::KeygenMenuHighGradeKeySize:
263 return IDS_KEYGEN_HIGH_GRADE_KEY;
264 case WebLocalizedString::KeygenMenuMediumGradeKeySize:
265 return IDS_KEYGEN_MED_GRADE_KEY;
266 case WebLocalizedString::MissingPluginText:
267 return IDS_PLUGIN_INITIALIZATION_ERROR;
268 case WebLocalizedString::MultipleFileUploadText:
269 return IDS_FORM_FILE_MULTIPLE_UPLOAD;
270 case WebLocalizedString::OtherColorLabel:
271 return IDS_FORM_OTHER_COLOR_LABEL;
272 case WebLocalizedString::OtherDateLabel:
273 return IDS_FORM_OTHER_DATE_LABEL;
274 case WebLocalizedString::OtherMonthLabel:
275 return IDS_FORM_OTHER_MONTH_LABEL;
276 case WebLocalizedString::OtherTimeLabel:
277 return IDS_FORM_OTHER_TIME_LABEL;
278 case WebLocalizedString::OtherWeekLabel:
279 return IDS_FORM_OTHER_WEEK_LABEL;
280 case WebLocalizedString::PlaceholderForDayOfMonthField:
281 return IDS_FORM_PLACEHOLDER_FOR_DAY_OF_MONTH_FIELD;
282 case WebLocalizedString::PlaceholderForMonthField:
283 return IDS_FORM_PLACEHOLDER_FOR_MONTH_FIELD;
284 case WebLocalizedString::PlaceholderForYearField:
285 return IDS_FORM_PLACEHOLDER_FOR_YEAR_FIELD;
286 case WebLocalizedString::ResetButtonDefaultLabel:
287 return IDS_FORM_RESET_LABEL;
288 case WebLocalizedString::SearchableIndexIntroduction:
289 return IDS_SEARCHABLE_INDEX_INTRO;
290 case WebLocalizedString::SearchMenuClearRecentSearchesText:
291 return IDS_RECENT_SEARCHES_CLEAR;
292 case WebLocalizedString::SearchMenuNoRecentSearchesText:
293 return IDS_RECENT_SEARCHES_NONE;
294 case WebLocalizedString::SearchMenuRecentSearchesText:
295 return IDS_RECENT_SEARCHES;
296 case WebLocalizedString::SubmitButtonDefaultLabel:
297 return IDS_FORM_SUBMIT_LABEL;
298 case WebLocalizedString::ThisMonthButtonLabel:
299 return IDS_FORM_THIS_MONTH_LABEL;
300 case WebLocalizedString::ThisWeekButtonLabel:
301 return IDS_FORM_THIS_WEEK_LABEL;
302 case WebLocalizedString::ValidationBadInputForDateTime:
303 return IDS_FORM_VALIDATION_BAD_INPUT_DATETIME;
304 case WebLocalizedString::ValidationBadInputForNumber:
305 return IDS_FORM_VALIDATION_BAD_INPUT_NUMBER;
306 case WebLocalizedString::ValidationPatternMismatch:
307 return IDS_FORM_VALIDATION_PATTERN_MISMATCH;
308 case WebLocalizedString::ValidationRangeOverflow:
309 return IDS_FORM_VALIDATION_RANGE_OVERFLOW;
310 case WebLocalizedString::ValidationRangeOverflowDateTime:
311 return IDS_FORM_VALIDATION_RANGE_OVERFLOW_DATETIME;
312 case WebLocalizedString::ValidationRangeUnderflow:
313 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW;
314 case WebLocalizedString::ValidationRangeUnderflowDateTime:
315 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW_DATETIME;
316 case WebLocalizedString::ValidationStepMismatch:
317 return IDS_FORM_VALIDATION_STEP_MISMATCH;
318 case WebLocalizedString::ValidationStepMismatchCloseToLimit:
319 return IDS_FORM_VALIDATION_STEP_MISMATCH_CLOSE_TO_LIMIT;
320 case WebLocalizedString::ValidationTooLong:
321 return IDS_FORM_VALIDATION_TOO_LONG;
322 case WebLocalizedString::ValidationTypeMismatch:
323 return IDS_FORM_VALIDATION_TYPE_MISMATCH;
324 case WebLocalizedString::ValidationTypeMismatchForEmail:
325 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL;
326 case WebLocalizedString::ValidationTypeMismatchForEmailEmpty:
327 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY;
328 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyDomain:
329 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_DOMAIN;
330 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyLocal:
331 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_LOCAL;
332 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDomain:
333 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOMAIN;
334 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots:
335 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOTS;
336 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidLocal:
337 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_LOCAL;
338 case WebLocalizedString::ValidationTypeMismatchForEmailNoAtSign:
339 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_NO_AT_SIGN;
340 case WebLocalizedString::ValidationTypeMismatchForMultipleEmail:
341 return IDS_FORM_VALIDATION_TYPE_MISMATCH_MULTIPLE_EMAIL;
342 case WebLocalizedString::ValidationTypeMismatchForURL:
343 return IDS_FORM_VALIDATION_TYPE_MISMATCH_URL;
344 case WebLocalizedString::ValidationValueMissing:
345 return IDS_FORM_VALIDATION_VALUE_MISSING;
346 case WebLocalizedString::ValidationValueMissingForCheckbox:
347 return IDS_FORM_VALIDATION_VALUE_MISSING_CHECKBOX;
348 case WebLocalizedString::ValidationValueMissingForFile:
349 return IDS_FORM_VALIDATION_VALUE_MISSING_FILE;
350 case WebLocalizedString::ValidationValueMissingForMultipleFile:
351 return IDS_FORM_VALIDATION_VALUE_MISSING_MULTIPLE_FILE;
352 case WebLocalizedString::ValidationValueMissingForRadio:
353 return IDS_FORM_VALIDATION_VALUE_MISSING_RADIO;
354 case WebLocalizedString::ValidationValueMissingForSelect:
355 return IDS_FORM_VALIDATION_VALUE_MISSING_SELECT;
356 case WebLocalizedString::WeekFormatTemplate:
357 return IDS_FORM_INPUT_WEEK_TEMPLATE;
358 case WebLocalizedString::WeekNumberLabel:
359 return IDS_FORM_WEEK_NUMBER_LABEL;
360 // This "default:" line exists to avoid compile warnings about enum
361 // coverage when we add a new symbol to WebLocalizedString.h in WebKit.
362 // After a planned WebKit patch is landed, we need to add a case statement
363 // for the added symbol here.
364 default:
365 break;
367 return -1;
370 WebKitPlatformSupportImpl::WebKitPlatformSupportImpl()
371 : main_loop_(base::MessageLoop::current()),
372 shared_timer_func_(NULL),
373 shared_timer_fire_time_(0.0),
374 shared_timer_fire_time_was_set_while_suspended_(false),
375 shared_timer_suspended_(0) {}
377 WebKitPlatformSupportImpl::~WebKitPlatformSupportImpl() {
380 WebURLLoader* WebKitPlatformSupportImpl::createURLLoader() {
381 return new WebURLLoaderImpl(this);
384 WebSocketStreamHandle* WebKitPlatformSupportImpl::createSocketStreamHandle() {
385 return new WebSocketStreamHandleImpl(this);
388 WebString WebKitPlatformSupportImpl::userAgent(const WebURL& url) {
389 return WebString::fromUTF8(webkit_glue::GetUserAgent(url));
392 WebData WebKitPlatformSupportImpl::parseDataURL(
393 const WebURL& url,
394 WebString& mimetype_out,
395 WebString& charset_out) {
396 std::string mime_type, char_set, data;
397 if (net::DataURL::Parse(url, &mime_type, &char_set, &data)
398 && net::IsSupportedMimeType(mime_type)) {
399 mimetype_out = WebString::fromUTF8(mime_type);
400 charset_out = WebString::fromUTF8(char_set);
401 return data;
403 return WebData();
406 WebURLError WebKitPlatformSupportImpl::cancelledError(
407 const WebURL& unreachableURL) const {
408 return WebURLLoaderImpl::CreateError(unreachableURL, net::ERR_ABORTED);
411 void WebKitPlatformSupportImpl::decrementStatsCounter(const char* name) {
412 base::StatsCounter(name).Decrement();
415 void WebKitPlatformSupportImpl::incrementStatsCounter(const char* name) {
416 base::StatsCounter(name).Increment();
419 void WebKitPlatformSupportImpl::histogramCustomCounts(
420 const char* name, int sample, int min, int max, int bucket_count) {
421 // Copied from histogram macro, but without the static variable caching
422 // the histogram because name is dynamic.
423 base::HistogramBase* counter =
424 base::Histogram::FactoryGet(name, min, max, bucket_count,
425 base::HistogramBase::kUmaTargetedHistogramFlag);
426 DCHECK_EQ(name, counter->histogram_name());
427 counter->Add(sample);
430 void WebKitPlatformSupportImpl::histogramEnumeration(
431 const char* name, int sample, int boundary_value) {
432 // Copied from histogram macro, but without the static variable caching
433 // the histogram because name is dynamic.
434 base::HistogramBase* counter =
435 base::LinearHistogram::FactoryGet(name, 1, boundary_value,
436 boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
437 DCHECK_EQ(name, counter->histogram_name());
438 counter->Add(sample);
441 void WebKitPlatformSupportImpl::histogramSparse(const char* name, int sample) {
442 // For sparse histograms, we can use the macro, as it does not incorporate a
443 // static.
444 UMA_HISTOGRAM_SPARSE_SLOWLY(name, sample);
447 const unsigned char* WebKitPlatformSupportImpl::getTraceCategoryEnabledFlag(
448 const char* category_group) {
449 return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(category_group);
452 long* WebKitPlatformSupportImpl::getTraceSamplingState(
453 const unsigned thread_bucket) {
454 switch (thread_bucket) {
455 case 0:
456 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(0));
457 case 1:
458 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(1));
459 case 2:
460 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(2));
461 default:
462 NOTREACHED() << "Unknown thread bucket type.";
464 return NULL;
467 void WebKitPlatformSupportImpl::addTraceEvent(
468 char phase,
469 const unsigned char* category_group_enabled,
470 const char* name,
471 unsigned long long id,
472 int num_args,
473 const char** arg_names,
474 const unsigned char* arg_types,
475 const unsigned long long* arg_values,
476 unsigned char flags) {
477 TRACE_EVENT_API_ADD_TRACE_EVENT(phase, category_group_enabled, name, id,
478 num_args, arg_names, arg_types,
479 arg_values, NULL, flags);
483 namespace {
485 WebData loadAudioSpatializationResource(WebKitPlatformSupportImpl* platform,
486 const char* name) {
487 #ifdef IDR_AUDIO_SPATIALIZATION_COMPOSITE
488 if (!strcmp(name, "Composite")) {
489 base::StringPiece resource =
490 platform->GetDataResource(IDR_AUDIO_SPATIALIZATION_COMPOSITE,
491 ui::SCALE_FACTOR_NONE);
492 return WebData(resource.data(), resource.size());
494 #endif
496 #ifdef IDR_AUDIO_SPATIALIZATION_T000_P000
497 const size_t kExpectedSpatializationNameLength = 31;
498 if (strlen(name) != kExpectedSpatializationNameLength) {
499 return WebData();
502 // Extract the azimuth and elevation from the resource name.
503 int azimuth = 0;
504 int elevation = 0;
505 int values_parsed =
506 sscanf(name, "IRC_Composite_C_R0195_T%3d_P%3d", &azimuth, &elevation);
507 if (values_parsed != 2) {
508 return WebData();
511 // The resource index values go through the elevations first, then azimuths.
512 const int kAngleSpacing = 15;
514 // 0 <= elevation <= 90 (or 315 <= elevation <= 345)
515 // in increments of 15 degrees.
516 int elevation_index =
517 elevation <= 90 ? elevation / kAngleSpacing :
518 7 + (elevation - 315) / kAngleSpacing;
519 bool is_elevation_index_good = 0 <= elevation_index && elevation_index < 10;
521 // 0 <= azimuth < 360 in increments of 15 degrees.
522 int azimuth_index = azimuth / kAngleSpacing;
523 bool is_azimuth_index_good = 0 <= azimuth_index && azimuth_index < 24;
525 const int kNumberOfElevations = 10;
526 const int kNumberOfAudioResources = 240;
527 int resource_index = kNumberOfElevations * azimuth_index + elevation_index;
528 bool is_resource_index_good = 0 <= resource_index &&
529 resource_index < kNumberOfAudioResources;
531 if (is_azimuth_index_good && is_elevation_index_good &&
532 is_resource_index_good) {
533 const int kFirstAudioResourceIndex = IDR_AUDIO_SPATIALIZATION_T000_P000;
534 base::StringPiece resource =
535 platform->GetDataResource(kFirstAudioResourceIndex + resource_index,
536 ui::SCALE_FACTOR_NONE);
537 return WebData(resource.data(), resource.size());
539 #endif // IDR_AUDIO_SPATIALIZATION_T000_P000
541 NOTREACHED();
542 return WebData();
545 struct DataResource {
546 const char* name;
547 int id;
548 ui::ScaleFactor scale_factor;
551 const DataResource kDataResources[] = {
552 { "missingImage", IDR_BROKENIMAGE, ui::SCALE_FACTOR_100P },
553 { "missingImage@2x", IDR_BROKENIMAGE, ui::SCALE_FACTOR_200P },
554 { "mediaplayerPause", IDR_MEDIAPLAYER_PAUSE_BUTTON, ui::SCALE_FACTOR_100P },
555 { "mediaplayerPauseHover",
556 IDR_MEDIAPLAYER_PAUSE_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
557 { "mediaplayerPauseDown",
558 IDR_MEDIAPLAYER_PAUSE_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
559 { "mediaplayerPlay", IDR_MEDIAPLAYER_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
560 { "mediaplayerPlayHover",
561 IDR_MEDIAPLAYER_PLAY_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
562 { "mediaplayerPlayDown",
563 IDR_MEDIAPLAYER_PLAY_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
564 { "mediaplayerPlayDisabled",
565 IDR_MEDIAPLAYER_PLAY_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
566 { "mediaplayerSoundLevel3",
567 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON, ui::SCALE_FACTOR_100P },
568 { "mediaplayerSoundLevel3Hover",
569 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
570 { "mediaplayerSoundLevel3Down",
571 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
572 { "mediaplayerSoundLevel2",
573 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON, ui::SCALE_FACTOR_100P },
574 { "mediaplayerSoundLevel2Hover",
575 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
576 { "mediaplayerSoundLevel2Down",
577 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
578 { "mediaplayerSoundLevel1",
579 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON, ui::SCALE_FACTOR_100P },
580 { "mediaplayerSoundLevel1Hover",
581 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
582 { "mediaplayerSoundLevel1Down",
583 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
584 { "mediaplayerSoundLevel0",
585 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON, ui::SCALE_FACTOR_100P },
586 { "mediaplayerSoundLevel0Hover",
587 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
588 { "mediaplayerSoundLevel0Down",
589 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
590 { "mediaplayerSoundDisabled",
591 IDR_MEDIAPLAYER_SOUND_DISABLED, ui::SCALE_FACTOR_100P },
592 { "mediaplayerSliderThumb",
593 IDR_MEDIAPLAYER_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
594 { "mediaplayerSliderThumbHover",
595 IDR_MEDIAPLAYER_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
596 { "mediaplayerSliderThumbDown",
597 IDR_MEDIAPLAYER_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
598 { "mediaplayerVolumeSliderThumb",
599 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
600 { "mediaplayerVolumeSliderThumbHover",
601 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
602 { "mediaplayerVolumeSliderThumbDown",
603 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
604 { "mediaplayerVolumeSliderThumbDisabled",
605 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DISABLED, ui::SCALE_FACTOR_100P },
606 { "mediaplayerClosedCaption",
607 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON, ui::SCALE_FACTOR_100P },
608 { "mediaplayerClosedCaptionHover",
609 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
610 { "mediaplayerClosedCaptionDown",
611 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
612 { "mediaplayerClosedCaptionDisabled",
613 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
614 { "mediaplayerFullscreen",
615 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON, ui::SCALE_FACTOR_100P },
616 { "mediaplayerFullscreenHover",
617 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
618 { "mediaplayerFullscreenDown",
619 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
620 { "mediaplayerFullscreenDisabled",
621 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
622 #if defined(OS_ANDROID)
623 { "mediaplayerOverlayPlay",
624 IDR_MEDIAPLAYER_OVERLAY_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
625 #endif
626 #if defined(OS_MACOSX)
627 { "overhangPattern", IDR_OVERHANG_PATTERN, ui::SCALE_FACTOR_100P },
628 { "overhangShadow", IDR_OVERHANG_SHADOW, ui::SCALE_FACTOR_100P },
629 #endif
630 { "panIcon", IDR_PAN_SCROLL_ICON, ui::SCALE_FACTOR_100P },
631 { "searchCancel", IDR_SEARCH_CANCEL, ui::SCALE_FACTOR_100P },
632 { "searchCancelPressed", IDR_SEARCH_CANCEL_PRESSED, ui::SCALE_FACTOR_100P },
633 { "searchMagnifier", IDR_SEARCH_MAGNIFIER, ui::SCALE_FACTOR_100P },
634 { "searchMagnifierResults",
635 IDR_SEARCH_MAGNIFIER_RESULTS, ui::SCALE_FACTOR_100P },
636 { "textAreaResizeCorner", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_100P },
637 { "textAreaResizeCorner@2x", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_200P },
638 { "inputSpeech", IDR_INPUT_SPEECH, ui::SCALE_FACTOR_100P },
639 { "inputSpeechRecording", IDR_INPUT_SPEECH_RECORDING, ui::SCALE_FACTOR_100P },
640 { "inputSpeechWaiting", IDR_INPUT_SPEECH_WAITING, ui::SCALE_FACTOR_100P },
641 { "americanExpressCC", IDR_AUTOFILL_CC_AMEX, ui::SCALE_FACTOR_100P },
642 { "dinersCC", IDR_AUTOFILL_CC_DINERS, ui::SCALE_FACTOR_100P },
643 { "discoverCC", IDR_AUTOFILL_CC_DISCOVER, ui::SCALE_FACTOR_100P },
644 { "genericCC", IDR_AUTOFILL_CC_GENERIC, ui::SCALE_FACTOR_100P },
645 { "jcbCC", IDR_AUTOFILL_CC_JCB, ui::SCALE_FACTOR_100P },
646 { "masterCardCC", IDR_AUTOFILL_CC_MASTERCARD, ui::SCALE_FACTOR_100P },
647 { "visaCC", IDR_AUTOFILL_CC_VISA, ui::SCALE_FACTOR_100P },
648 { "generatePassword", IDR_PASSWORD_GENERATION_ICON, ui::SCALE_FACTOR_100P },
649 { "generatePasswordHover",
650 IDR_PASSWORD_GENERATION_ICON_HOVER, ui::SCALE_FACTOR_100P },
651 { "syntheticTouchCursor",
652 IDR_SYNTHETIC_TOUCH_CURSOR, ui::SCALE_FACTOR_100P },
655 } // namespace
657 WebData WebKitPlatformSupportImpl::loadResource(const char* name) {
658 // Some clients will call into this method with an empty |name| when they have
659 // optional resources. For example, the PopupMenuChromium code can have icons
660 // for some Autofill items but not for others.
661 if (!strlen(name))
662 return WebData();
664 // Check the name prefix to see if it's an audio resource.
665 if (StartsWithASCII(name, "IRC_Composite", true) ||
666 StartsWithASCII(name, "Composite", true))
667 return loadAudioSpatializationResource(this, name);
669 // TODO(flackr): We should use a better than linear search here, a trie would
670 // be ideal.
671 for (size_t i = 0; i < arraysize(kDataResources); ++i) {
672 if (!strcmp(name, kDataResources[i].name)) {
673 base::StringPiece resource =
674 GetDataResource(kDataResources[i].id,
675 kDataResources[i].scale_factor);
676 return WebData(resource.data(), resource.size());
680 NOTREACHED() << "Unknown image resource " << name;
681 return WebData();
684 WebString WebKitPlatformSupportImpl::queryLocalizedString(
685 WebLocalizedString::Name name) {
686 int message_id = ToMessageID(name);
687 if (message_id < 0)
688 return WebString();
689 return GetLocalizedString(message_id);
692 WebString WebKitPlatformSupportImpl::queryLocalizedString(
693 WebLocalizedString::Name name, int numeric_value) {
694 return queryLocalizedString(name, base::IntToString16(numeric_value));
697 WebString WebKitPlatformSupportImpl::queryLocalizedString(
698 WebLocalizedString::Name name, const WebString& value) {
699 int message_id = ToMessageID(name);
700 if (message_id < 0)
701 return WebString();
702 return ReplaceStringPlaceholders(GetLocalizedString(message_id), value, NULL);
705 WebString WebKitPlatformSupportImpl::queryLocalizedString(
706 WebLocalizedString::Name name,
707 const WebString& value1,
708 const WebString& value2) {
709 int message_id = ToMessageID(name);
710 if (message_id < 0)
711 return WebString();
712 std::vector<base::string16> values;
713 values.reserve(2);
714 values.push_back(value1);
715 values.push_back(value2);
716 return ReplaceStringPlaceholders(
717 GetLocalizedString(message_id), values, NULL);
720 double WebKitPlatformSupportImpl::currentTime() {
721 return base::Time::Now().ToDoubleT();
724 double WebKitPlatformSupportImpl::monotonicallyIncreasingTime() {
725 return base::TimeTicks::Now().ToInternalValue() /
726 static_cast<double>(base::Time::kMicrosecondsPerSecond);
729 void WebKitPlatformSupportImpl::cryptographicallyRandomValues(
730 unsigned char* buffer, size_t length) {
731 base::RandBytes(buffer, length);
734 void WebKitPlatformSupportImpl::setSharedTimerFiredFunction(void (*func)()) {
735 shared_timer_func_ = func;
738 void WebKitPlatformSupportImpl::setSharedTimerFireInterval(
739 double interval_seconds) {
740 shared_timer_fire_time_ = interval_seconds + monotonicallyIncreasingTime();
741 if (shared_timer_suspended_) {
742 shared_timer_fire_time_was_set_while_suspended_ = true;
743 return;
746 // By converting between double and int64 representation, we run the risk
747 // of losing precision due to rounding errors. Performing computations in
748 // microseconds reduces this risk somewhat. But there still is the potential
749 // of us computing a fire time for the timer that is shorter than what we
750 // need.
751 // As the event loop will check event deadlines prior to actually firing
752 // them, there is a risk of needlessly rescheduling events and of
753 // needlessly looping if sleep times are too short even by small amounts.
754 // This results in measurable performance degradation unless we use ceil() to
755 // always round up the sleep times.
756 int64 interval = static_cast<int64>(
757 ceil(interval_seconds * base::Time::kMillisecondsPerSecond)
758 * base::Time::kMicrosecondsPerMillisecond);
760 if (interval < 0)
761 interval = 0;
763 shared_timer_.Stop();
764 shared_timer_.Start(FROM_HERE, base::TimeDelta::FromMicroseconds(interval),
765 this, &WebKitPlatformSupportImpl::DoTimeout);
766 OnStartSharedTimer(base::TimeDelta::FromMicroseconds(interval));
769 void WebKitPlatformSupportImpl::stopSharedTimer() {
770 shared_timer_.Stop();
773 void WebKitPlatformSupportImpl::callOnMainThread(
774 void (*func)(void*), void* context) {
775 main_loop_->PostTask(FROM_HERE, base::Bind(func, context));
778 base::PlatformFile WebKitPlatformSupportImpl::databaseOpenFile(
779 const WebKit::WebString& vfs_file_name, int desired_flags) {
780 return base::kInvalidPlatformFileValue;
783 int WebKitPlatformSupportImpl::databaseDeleteFile(
784 const WebKit::WebString& vfs_file_name, bool sync_dir) {
785 return -1;
788 long WebKitPlatformSupportImpl::databaseGetFileAttributes(
789 const WebKit::WebString& vfs_file_name) {
790 return 0;
793 long long WebKitPlatformSupportImpl::databaseGetFileSize(
794 const WebKit::WebString& vfs_file_name) {
795 return 0;
798 long long WebKitPlatformSupportImpl::databaseGetSpaceAvailableForOrigin(
799 const WebKit::WebString& origin_identifier) {
800 return 0;
803 WebKit::WebString WebKitPlatformSupportImpl::signedPublicKeyAndChallengeString(
804 unsigned key_size_index,
805 const WebKit::WebString& challenge,
806 const WebKit::WebURL& url) {
807 return WebKit::WebString("");
810 static scoped_ptr<base::ProcessMetrics> CurrentProcessMetrics() {
811 using base::ProcessMetrics;
812 #if defined(OS_MACOSX)
813 return scoped_ptr<ProcessMetrics>(
814 // The default port provider is sufficient to get data for the current
815 // process.
816 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle(),
817 NULL));
818 #else
819 return scoped_ptr<ProcessMetrics>(
820 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle()));
821 #endif
824 static size_t getMemoryUsageMB(bool bypass_cache) {
825 size_t current_mem_usage = 0;
826 MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::GetInstance();
827 if (!bypass_cache &&
828 mem_usage_cache_singleton->IsCachedValueValid(&current_mem_usage))
829 return current_mem_usage;
831 current_mem_usage = MemoryUsageKB() >> 10;
832 mem_usage_cache_singleton->SetMemoryValue(current_mem_usage);
833 return current_mem_usage;
836 size_t WebKitPlatformSupportImpl::memoryUsageMB() {
837 return getMemoryUsageMB(false);
840 size_t WebKitPlatformSupportImpl::actualMemoryUsageMB() {
841 return getMemoryUsageMB(true);
844 void WebKitPlatformSupportImpl::startHeapProfiling(
845 const WebKit::WebString& prefix) {
846 // FIXME(morrita): Make this built on windows.
847 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
848 HeapProfilerStart(prefix.utf8().data());
849 #endif
852 void WebKitPlatformSupportImpl::stopHeapProfiling() {
853 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
854 HeapProfilerStop();
855 #endif
858 void WebKitPlatformSupportImpl::dumpHeapProfiling(
859 const WebKit::WebString& reason) {
860 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
861 HeapProfilerDump(reason.utf8().data());
862 #endif
865 WebString WebKitPlatformSupportImpl::getHeapProfile() {
866 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
867 char* data = GetHeapProfile();
868 WebString result = WebString::fromUTF8(std::string(data));
869 free(data);
870 return result;
871 #else
872 return WebString();
873 #endif
876 bool WebKitPlatformSupportImpl::processMemorySizesInBytes(
877 size_t* private_bytes,
878 size_t* shared_bytes) {
879 return CurrentProcessMetrics()->GetMemoryBytes(private_bytes, shared_bytes);
882 bool WebKitPlatformSupportImpl::memoryAllocatorWasteInBytes(size_t* size) {
883 return base::allocator::GetAllocatorWasteSize(size);
886 void WebKitPlatformSupportImpl::SuspendSharedTimer() {
887 ++shared_timer_suspended_;
890 void WebKitPlatformSupportImpl::ResumeSharedTimer() {
891 // The shared timer may have fired or been adjusted while we were suspended.
892 if (--shared_timer_suspended_ == 0 &&
893 (!shared_timer_.IsRunning() ||
894 shared_timer_fire_time_was_set_while_suspended_)) {
895 shared_timer_fire_time_was_set_while_suspended_ = false;
896 setSharedTimerFireInterval(
897 shared_timer_fire_time_ - monotonicallyIncreasingTime());
901 } // namespace webkit_glue