[SyncFS] Build indexes from FileTracker entries on disk.
[chromium-blink-merge.git] / content / child / blink_platform_impl.cc
blobf0544a86736951fe7c57badf7392f37adb9a21d4
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 "content/child/child_thread.h"
30 #include "content/child/content_child_helpers.h"
31 #include "content/child/fling_curve_configuration.h"
32 #include "content/child/web_discardable_memory_impl.h"
33 #include "content/child/web_socket_stream_handle_impl.h"
34 #include "content/child/web_url_loader_impl.h"
35 #include "content/child/websocket_bridge.h"
36 #include "content/child/webthread_impl.h"
37 #include "content/child/worker_task_runner.h"
38 #include "content/public/common/content_client.h"
39 #include "grit/blink_resources.h"
40 #include "grit/webkit_resources.h"
41 #include "grit/webkit_strings.h"
42 #include "net/base/data_url.h"
43 #include "net/base/mime_util.h"
44 #include "net/base/net_errors.h"
45 #include "third_party/WebKit/public/platform/WebConvertableToTraceFormat.h"
46 #include "third_party/WebKit/public/platform/WebData.h"
47 #include "third_party/WebKit/public/platform/WebString.h"
48 #include "third_party/WebKit/public/platform/WebWaitableEvent.h"
49 #include "ui/base/layout.h"
51 #if defined(OS_ANDROID)
52 #include "content/child/fling_animator_impl_android.h"
53 #endif
55 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
56 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
57 #endif
59 using blink::WebData;
60 using blink::WebFallbackThemeEngine;
61 using blink::WebLocalizedString;
62 using blink::WebString;
63 using blink::WebSocketStreamHandle;
64 using blink::WebThemeEngine;
65 using blink::WebURL;
66 using blink::WebURLError;
67 using blink::WebURLLoader;
69 namespace content {
71 namespace {
73 class WebWaitableEventImpl : public blink::WebWaitableEvent {
74 public:
75 WebWaitableEventImpl() : impl_(new base::WaitableEvent(false, false)) {}
76 virtual ~WebWaitableEventImpl() {}
78 virtual void wait() { impl_->Wait(); }
79 virtual void signal() { impl_->Signal(); }
81 base::WaitableEvent* impl() {
82 return impl_.get();
85 private:
86 scoped_ptr<base::WaitableEvent> impl_;
87 DISALLOW_COPY_AND_ASSIGN(WebWaitableEventImpl);
90 // A simple class to cache the memory usage for a given amount of time.
91 class MemoryUsageCache {
92 public:
93 // Retrieves the Singleton.
94 static MemoryUsageCache* GetInstance() {
95 return Singleton<MemoryUsageCache>::get();
98 MemoryUsageCache() : memory_value_(0) { Init(); }
99 ~MemoryUsageCache() {}
101 void Init() {
102 const unsigned int kCacheSeconds = 1;
103 cache_valid_time_ = base::TimeDelta::FromSeconds(kCacheSeconds);
106 // Returns true if the cached value is fresh.
107 // Returns false if the cached value is stale, or if |cached_value| is NULL.
108 bool IsCachedValueValid(size_t* cached_value) {
109 base::AutoLock scoped_lock(lock_);
110 if (!cached_value)
111 return false;
112 if (base::Time::Now() - last_updated_time_ > cache_valid_time_)
113 return false;
114 *cached_value = memory_value_;
115 return true;
118 // Setter for |memory_value_|, refreshes |last_updated_time_|.
119 void SetMemoryValue(const size_t value) {
120 base::AutoLock scoped_lock(lock_);
121 memory_value_ = value;
122 last_updated_time_ = base::Time::Now();
125 private:
126 // The cached memory value.
127 size_t memory_value_;
129 // How long the cached value should remain valid.
130 base::TimeDelta cache_valid_time_;
132 // The last time the cached value was updated.
133 base::Time last_updated_time_;
135 base::Lock lock_;
138 class ConvertableToTraceFormatWrapper
139 : public base::debug::ConvertableToTraceFormat {
140 public:
141 explicit ConvertableToTraceFormatWrapper(
142 const blink::WebConvertableToTraceFormat& convertable)
143 : convertable_(convertable) {}
144 virtual void AppendAsTraceFormat(std::string* out) const OVERRIDE {
145 *out += convertable_.asTraceFormat().utf8();
148 private:
149 virtual ~ConvertableToTraceFormatWrapper() {}
151 blink::WebConvertableToTraceFormat convertable_;
154 } // namespace
156 static int ToMessageID(WebLocalizedString::Name name) {
157 switch (name) {
158 case WebLocalizedString::AXAMPMFieldText:
159 return IDS_AX_AM_PM_FIELD_TEXT;
160 case WebLocalizedString::AXButtonActionVerb:
161 return IDS_AX_BUTTON_ACTION_VERB;
162 case WebLocalizedString::AXCheckedCheckBoxActionVerb:
163 return IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB;
164 case WebLocalizedString::AXDateTimeFieldEmptyValueText:
165 return IDS_AX_DATE_TIME_FIELD_EMPTY_VALUE_TEXT;
166 case WebLocalizedString::AXDayOfMonthFieldText:
167 return IDS_AX_DAY_OF_MONTH_FIELD_TEXT;
168 case WebLocalizedString::AXHeadingText:
169 return IDS_AX_ROLE_HEADING;
170 case WebLocalizedString::AXHourFieldText:
171 return IDS_AX_HOUR_FIELD_TEXT;
172 case WebLocalizedString::AXImageMapText:
173 return IDS_AX_ROLE_IMAGE_MAP;
174 case WebLocalizedString::AXLinkActionVerb:
175 return IDS_AX_LINK_ACTION_VERB;
176 case WebLocalizedString::AXLinkText:
177 return IDS_AX_ROLE_LINK;
178 case WebLocalizedString::AXListMarkerText:
179 return IDS_AX_ROLE_LIST_MARKER;
180 case WebLocalizedString::AXMediaDefault:
181 return IDS_AX_MEDIA_DEFAULT;
182 case WebLocalizedString::AXMediaAudioElement:
183 return IDS_AX_MEDIA_AUDIO_ELEMENT;
184 case WebLocalizedString::AXMediaVideoElement:
185 return IDS_AX_MEDIA_VIDEO_ELEMENT;
186 case WebLocalizedString::AXMediaMuteButton:
187 return IDS_AX_MEDIA_MUTE_BUTTON;
188 case WebLocalizedString::AXMediaUnMuteButton:
189 return IDS_AX_MEDIA_UNMUTE_BUTTON;
190 case WebLocalizedString::AXMediaPlayButton:
191 return IDS_AX_MEDIA_PLAY_BUTTON;
192 case WebLocalizedString::AXMediaPauseButton:
193 return IDS_AX_MEDIA_PAUSE_BUTTON;
194 case WebLocalizedString::AXMediaSlider:
195 return IDS_AX_MEDIA_SLIDER;
196 case WebLocalizedString::AXMediaSliderThumb:
197 return IDS_AX_MEDIA_SLIDER_THUMB;
198 case WebLocalizedString::AXMediaCurrentTimeDisplay:
199 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY;
200 case WebLocalizedString::AXMediaTimeRemainingDisplay:
201 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY;
202 case WebLocalizedString::AXMediaStatusDisplay:
203 return IDS_AX_MEDIA_STATUS_DISPLAY;
204 case WebLocalizedString::AXMediaEnterFullscreenButton:
205 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON;
206 case WebLocalizedString::AXMediaExitFullscreenButton:
207 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON;
208 case WebLocalizedString::AXMediaShowClosedCaptionsButton:
209 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON;
210 case WebLocalizedString::AXMediaHideClosedCaptionsButton:
211 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON;
212 case WebLocalizedString::AXMediaAudioElementHelp:
213 return IDS_AX_MEDIA_AUDIO_ELEMENT_HELP;
214 case WebLocalizedString::AXMediaVideoElementHelp:
215 return IDS_AX_MEDIA_VIDEO_ELEMENT_HELP;
216 case WebLocalizedString::AXMediaMuteButtonHelp:
217 return IDS_AX_MEDIA_MUTE_BUTTON_HELP;
218 case WebLocalizedString::AXMediaUnMuteButtonHelp:
219 return IDS_AX_MEDIA_UNMUTE_BUTTON_HELP;
220 case WebLocalizedString::AXMediaPlayButtonHelp:
221 return IDS_AX_MEDIA_PLAY_BUTTON_HELP;
222 case WebLocalizedString::AXMediaPauseButtonHelp:
223 return IDS_AX_MEDIA_PAUSE_BUTTON_HELP;
224 case WebLocalizedString::AXMediaSliderHelp:
225 return IDS_AX_MEDIA_SLIDER_HELP;
226 case WebLocalizedString::AXMediaSliderThumbHelp:
227 return IDS_AX_MEDIA_SLIDER_THUMB_HELP;
228 case WebLocalizedString::AXMediaCurrentTimeDisplayHelp:
229 return IDS_AX_MEDIA_CURRENT_TIME_DISPLAY_HELP;
230 case WebLocalizedString::AXMediaTimeRemainingDisplayHelp:
231 return IDS_AX_MEDIA_TIME_REMAINING_DISPLAY_HELP;
232 case WebLocalizedString::AXMediaStatusDisplayHelp:
233 return IDS_AX_MEDIA_STATUS_DISPLAY_HELP;
234 case WebLocalizedString::AXMediaEnterFullscreenButtonHelp:
235 return IDS_AX_MEDIA_ENTER_FULL_SCREEN_BUTTON_HELP;
236 case WebLocalizedString::AXMediaExitFullscreenButtonHelp:
237 return IDS_AX_MEDIA_EXIT_FULL_SCREEN_BUTTON_HELP;
238 case WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp:
239 return IDS_AX_MEDIA_SHOW_CLOSED_CAPTIONS_BUTTON_HELP;
240 case WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp:
241 return IDS_AX_MEDIA_HIDE_CLOSED_CAPTIONS_BUTTON_HELP;
242 case WebLocalizedString::AXMillisecondFieldText:
243 return IDS_AX_MILLISECOND_FIELD_TEXT;
244 case WebLocalizedString::AXMinuteFieldText:
245 return IDS_AX_MINUTE_FIELD_TEXT;
246 case WebLocalizedString::AXMonthFieldText:
247 return IDS_AX_MONTH_FIELD_TEXT;
248 case WebLocalizedString::AXRadioButtonActionVerb:
249 return IDS_AX_RADIO_BUTTON_ACTION_VERB;
250 case WebLocalizedString::AXSecondFieldText:
251 return IDS_AX_SECOND_FIELD_TEXT;
252 case WebLocalizedString::AXTextFieldActionVerb:
253 return IDS_AX_TEXT_FIELD_ACTION_VERB;
254 case WebLocalizedString::AXUncheckedCheckBoxActionVerb:
255 return IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB;
256 case WebLocalizedString::AXWebAreaText:
257 return IDS_AX_ROLE_WEB_AREA;
258 case WebLocalizedString::AXWeekOfYearFieldText:
259 return IDS_AX_WEEK_OF_YEAR_FIELD_TEXT;
260 case WebLocalizedString::AXYearFieldText:
261 return IDS_AX_YEAR_FIELD_TEXT;
262 case WebLocalizedString::CalendarClear:
263 return IDS_FORM_CALENDAR_CLEAR;
264 case WebLocalizedString::CalendarToday:
265 return IDS_FORM_CALENDAR_TODAY;
266 case WebLocalizedString::DateFormatDayInMonthLabel:
267 return IDS_FORM_DATE_FORMAT_DAY_IN_MONTH;
268 case WebLocalizedString::DateFormatMonthLabel:
269 return IDS_FORM_DATE_FORMAT_MONTH;
270 case WebLocalizedString::DateFormatYearLabel:
271 return IDS_FORM_DATE_FORMAT_YEAR;
272 case WebLocalizedString::DetailsLabel:
273 return IDS_DETAILS_WITHOUT_SUMMARY_LABEL;
274 case WebLocalizedString::FileButtonChooseFileLabel:
275 return IDS_FORM_FILE_BUTTON_LABEL;
276 case WebLocalizedString::FileButtonChooseMultipleFilesLabel:
277 return IDS_FORM_MULTIPLE_FILES_BUTTON_LABEL;
278 case WebLocalizedString::FileButtonNoFileSelectedLabel:
279 return IDS_FORM_FILE_NO_FILE_LABEL;
280 case WebLocalizedString::InputElementAltText:
281 return IDS_FORM_INPUT_ALT;
282 case WebLocalizedString::KeygenMenuHighGradeKeySize:
283 return IDS_KEYGEN_HIGH_GRADE_KEY;
284 case WebLocalizedString::KeygenMenuMediumGradeKeySize:
285 return IDS_KEYGEN_MED_GRADE_KEY;
286 case WebLocalizedString::MissingPluginText:
287 return IDS_PLUGIN_INITIALIZATION_ERROR;
288 case WebLocalizedString::MultipleFileUploadText:
289 return IDS_FORM_FILE_MULTIPLE_UPLOAD;
290 case WebLocalizedString::OtherColorLabel:
291 return IDS_FORM_OTHER_COLOR_LABEL;
292 case WebLocalizedString::OtherDateLabel:
293 return IDS_FORM_OTHER_DATE_LABEL;
294 case WebLocalizedString::OtherMonthLabel:
295 return IDS_FORM_OTHER_MONTH_LABEL;
296 case WebLocalizedString::OtherTimeLabel:
297 return IDS_FORM_OTHER_TIME_LABEL;
298 case WebLocalizedString::OtherWeekLabel:
299 return IDS_FORM_OTHER_WEEK_LABEL;
300 case WebLocalizedString::PlaceholderForDayOfMonthField:
301 return IDS_FORM_PLACEHOLDER_FOR_DAY_OF_MONTH_FIELD;
302 case WebLocalizedString::PlaceholderForMonthField:
303 return IDS_FORM_PLACEHOLDER_FOR_MONTH_FIELD;
304 case WebLocalizedString::PlaceholderForYearField:
305 return IDS_FORM_PLACEHOLDER_FOR_YEAR_FIELD;
306 case WebLocalizedString::ResetButtonDefaultLabel:
307 return IDS_FORM_RESET_LABEL;
308 case WebLocalizedString::SearchableIndexIntroduction:
309 return IDS_SEARCHABLE_INDEX_INTRO;
310 case WebLocalizedString::SearchMenuClearRecentSearchesText:
311 return IDS_RECENT_SEARCHES_CLEAR;
312 case WebLocalizedString::SearchMenuNoRecentSearchesText:
313 return IDS_RECENT_SEARCHES_NONE;
314 case WebLocalizedString::SearchMenuRecentSearchesText:
315 return IDS_RECENT_SEARCHES;
316 case WebLocalizedString::SelectMenuListText:
317 return IDS_FORM_SELECT_MENU_LIST_TEXT;
318 case WebLocalizedString::SubmitButtonDefaultLabel:
319 return IDS_FORM_SUBMIT_LABEL;
320 case WebLocalizedString::ThisMonthButtonLabel:
321 return IDS_FORM_THIS_MONTH_LABEL;
322 case WebLocalizedString::ThisWeekButtonLabel:
323 return IDS_FORM_THIS_WEEK_LABEL;
324 case WebLocalizedString::ValidationBadInputForDateTime:
325 return IDS_FORM_VALIDATION_BAD_INPUT_DATETIME;
326 case WebLocalizedString::ValidationBadInputForNumber:
327 return IDS_FORM_VALIDATION_BAD_INPUT_NUMBER;
328 case WebLocalizedString::ValidationPatternMismatch:
329 return IDS_FORM_VALIDATION_PATTERN_MISMATCH;
330 case WebLocalizedString::ValidationRangeOverflow:
331 return IDS_FORM_VALIDATION_RANGE_OVERFLOW;
332 case WebLocalizedString::ValidationRangeOverflowDateTime:
333 return IDS_FORM_VALIDATION_RANGE_OVERFLOW_DATETIME;
334 case WebLocalizedString::ValidationRangeUnderflow:
335 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW;
336 case WebLocalizedString::ValidationRangeUnderflowDateTime:
337 return IDS_FORM_VALIDATION_RANGE_UNDERFLOW_DATETIME;
338 case WebLocalizedString::ValidationStepMismatch:
339 return IDS_FORM_VALIDATION_STEP_MISMATCH;
340 case WebLocalizedString::ValidationStepMismatchCloseToLimit:
341 return IDS_FORM_VALIDATION_STEP_MISMATCH_CLOSE_TO_LIMIT;
342 case WebLocalizedString::ValidationTooLong:
343 return IDS_FORM_VALIDATION_TOO_LONG;
344 case WebLocalizedString::ValidationTypeMismatch:
345 return IDS_FORM_VALIDATION_TYPE_MISMATCH;
346 case WebLocalizedString::ValidationTypeMismatchForEmail:
347 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL;
348 case WebLocalizedString::ValidationTypeMismatchForEmailEmpty:
349 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY;
350 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyDomain:
351 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_DOMAIN;
352 case WebLocalizedString::ValidationTypeMismatchForEmailEmptyLocal:
353 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_EMPTY_LOCAL;
354 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDomain:
355 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOMAIN;
356 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots:
357 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_DOTS;
358 case WebLocalizedString::ValidationTypeMismatchForEmailInvalidLocal:
359 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_INVALID_LOCAL;
360 case WebLocalizedString::ValidationTypeMismatchForEmailNoAtSign:
361 return IDS_FORM_VALIDATION_TYPE_MISMATCH_EMAIL_NO_AT_SIGN;
362 case WebLocalizedString::ValidationTypeMismatchForMultipleEmail:
363 return IDS_FORM_VALIDATION_TYPE_MISMATCH_MULTIPLE_EMAIL;
364 case WebLocalizedString::ValidationTypeMismatchForURL:
365 return IDS_FORM_VALIDATION_TYPE_MISMATCH_URL;
366 case WebLocalizedString::ValidationValueMissing:
367 return IDS_FORM_VALIDATION_VALUE_MISSING;
368 case WebLocalizedString::ValidationValueMissingForCheckbox:
369 return IDS_FORM_VALIDATION_VALUE_MISSING_CHECKBOX;
370 case WebLocalizedString::ValidationValueMissingForFile:
371 return IDS_FORM_VALIDATION_VALUE_MISSING_FILE;
372 case WebLocalizedString::ValidationValueMissingForMultipleFile:
373 return IDS_FORM_VALIDATION_VALUE_MISSING_MULTIPLE_FILE;
374 case WebLocalizedString::ValidationValueMissingForRadio:
375 return IDS_FORM_VALIDATION_VALUE_MISSING_RADIO;
376 case WebLocalizedString::ValidationValueMissingForSelect:
377 return IDS_FORM_VALIDATION_VALUE_MISSING_SELECT;
378 case WebLocalizedString::WeekFormatTemplate:
379 return IDS_FORM_INPUT_WEEK_TEMPLATE;
380 case WebLocalizedString::WeekNumberLabel:
381 return IDS_FORM_WEEK_NUMBER_LABEL;
382 // This "default:" line exists to avoid compile warnings about enum
383 // coverage when we add a new symbol to WebLocalizedString.h in WebKit.
384 // After a planned WebKit patch is landed, we need to add a case statement
385 // for the added symbol here.
386 default:
387 break;
389 return -1;
392 BlinkPlatformImpl::BlinkPlatformImpl()
393 : main_loop_(base::MessageLoop::current()),
394 shared_timer_func_(NULL),
395 shared_timer_fire_time_(0.0),
396 shared_timer_fire_time_was_set_while_suspended_(false),
397 shared_timer_suspended_(0),
398 fling_curve_configuration_(new FlingCurveConfiguration),
399 current_thread_slot_(&DestroyCurrentThread) {}
401 BlinkPlatformImpl::~BlinkPlatformImpl() {
404 WebURLLoader* BlinkPlatformImpl::createURLLoader() {
405 ChildThread* child_thread = ChildThread::current();
406 // There may be no child thread in RenderViewTests. These tests can still use
407 // data URLs to bypass the ResourceDispatcher.
408 return new WebURLLoaderImpl(
409 child_thread ? child_thread->resource_dispatcher() : NULL);
412 WebSocketStreamHandle* BlinkPlatformImpl::createSocketStreamHandle() {
413 return new WebSocketStreamHandleImpl;
416 blink::WebSocketHandle* BlinkPlatformImpl::createWebSocketHandle() {
417 return new WebSocketBridge;
420 WebString BlinkPlatformImpl::userAgent() {
421 return WebString::fromUTF8(GetContentClient()->GetUserAgent());
424 WebData BlinkPlatformImpl::parseDataURL(const WebURL& url,
425 WebString& mimetype_out,
426 WebString& charset_out) {
427 std::string mime_type, char_set, data;
428 if (net::DataURL::Parse(url, &mime_type, &char_set, &data)
429 && net::IsSupportedMimeType(mime_type)) {
430 mimetype_out = WebString::fromUTF8(mime_type);
431 charset_out = WebString::fromUTF8(char_set);
432 return data;
434 return WebData();
437 WebURLError BlinkPlatformImpl::cancelledError(
438 const WebURL& unreachableURL) const {
439 return WebURLLoaderImpl::CreateError(unreachableURL, false, net::ERR_ABORTED);
442 blink::WebThread* BlinkPlatformImpl::createThread(const char* name) {
443 return new WebThreadImpl(name);
446 blink::WebThread* BlinkPlatformImpl::currentThread() {
447 WebThreadImplForMessageLoop* thread =
448 static_cast<WebThreadImplForMessageLoop*>(current_thread_slot_.Get());
449 if (thread)
450 return (thread);
452 scoped_refptr<base::MessageLoopProxy> message_loop =
453 base::MessageLoopProxy::current();
454 if (!message_loop.get())
455 return NULL;
457 thread = new WebThreadImplForMessageLoop(message_loop.get());
458 current_thread_slot_.Set(thread);
459 return thread;
462 blink::WebWaitableEvent* BlinkPlatformImpl::createWaitableEvent() {
463 return new WebWaitableEventImpl();
466 blink::WebWaitableEvent* BlinkPlatformImpl::waitMultipleEvents(
467 const blink::WebVector<blink::WebWaitableEvent*>& web_events) {
468 std::vector<base::WaitableEvent*> events;
469 for (size_t i = 0; i < web_events.size(); ++i)
470 events.push_back(static_cast<WebWaitableEventImpl*>(web_events[i])->impl());
471 size_t idx = base::WaitableEvent::WaitMany(
472 vector_as_array(&events), events.size());
473 DCHECK_LT(idx, web_events.size());
474 return web_events[idx];
477 void BlinkPlatformImpl::decrementStatsCounter(const char* name) {
478 base::StatsCounter(name).Decrement();
481 void BlinkPlatformImpl::incrementStatsCounter(const char* name) {
482 base::StatsCounter(name).Increment();
485 void BlinkPlatformImpl::histogramCustomCounts(
486 const char* name, int sample, int min, int max, int bucket_count) {
487 // Copied from histogram macro, but without the static variable caching
488 // the histogram because name is dynamic.
489 base::HistogramBase* counter =
490 base::Histogram::FactoryGet(name, min, max, bucket_count,
491 base::HistogramBase::kUmaTargetedHistogramFlag);
492 DCHECK_EQ(name, counter->histogram_name());
493 counter->Add(sample);
496 void BlinkPlatformImpl::histogramEnumeration(
497 const char* name, int sample, int boundary_value) {
498 // Copied from histogram macro, but without the static variable caching
499 // the histogram because name is dynamic.
500 base::HistogramBase* counter =
501 base::LinearHistogram::FactoryGet(name, 1, boundary_value,
502 boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
503 DCHECK_EQ(name, counter->histogram_name());
504 counter->Add(sample);
507 void BlinkPlatformImpl::histogramSparse(const char* name, int sample) {
508 // For sparse histograms, we can use the macro, as it does not incorporate a
509 // static.
510 UMA_HISTOGRAM_SPARSE_SLOWLY(name, sample);
513 const unsigned char* BlinkPlatformImpl::getTraceCategoryEnabledFlag(
514 const char* category_group) {
515 return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(category_group);
518 long* BlinkPlatformImpl::getTraceSamplingState(
519 const unsigned thread_bucket) {
520 switch (thread_bucket) {
521 case 0:
522 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(0));
523 case 1:
524 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(1));
525 case 2:
526 return reinterpret_cast<long*>(&TRACE_EVENT_API_THREAD_BUCKET(2));
527 default:
528 NOTREACHED() << "Unknown thread bucket type.";
530 return NULL;
533 COMPILE_ASSERT(
534 sizeof(blink::Platform::TraceEventHandle) ==
535 sizeof(base::debug::TraceEventHandle),
536 TraceEventHandle_types_must_be_same_size);
538 blink::Platform::TraceEventHandle BlinkPlatformImpl::addTraceEvent(
539 char phase,
540 const unsigned char* category_group_enabled,
541 const char* name,
542 unsigned long long id,
543 int num_args,
544 const char** arg_names,
545 const unsigned char* arg_types,
546 const unsigned long long* arg_values,
547 unsigned char flags) {
548 base::debug::TraceEventHandle handle = TRACE_EVENT_API_ADD_TRACE_EVENT(
549 phase, category_group_enabled, name, id,
550 num_args, arg_names, arg_types, arg_values, NULL, flags);
551 blink::Platform::TraceEventHandle result;
552 memcpy(&result, &handle, sizeof(result));
553 return result;
556 blink::Platform::TraceEventHandle BlinkPlatformImpl::addTraceEvent(
557 char phase,
558 const unsigned char* category_group_enabled,
559 const char* name,
560 unsigned long long id,
561 int num_args,
562 const char** arg_names,
563 const unsigned char* arg_types,
564 const unsigned long long* arg_values,
565 const blink::WebConvertableToTraceFormat* convertable_values,
566 unsigned char flags) {
567 scoped_refptr<base::debug::ConvertableToTraceFormat> convertable_wrappers[2];
568 if (convertable_values) {
569 size_t size = std::min(static_cast<size_t>(num_args),
570 arraysize(convertable_wrappers));
571 for (size_t i = 0; i < size; ++i) {
572 if (arg_types[i] == TRACE_VALUE_TYPE_CONVERTABLE) {
573 convertable_wrappers[i] =
574 new ConvertableToTraceFormatWrapper(convertable_values[i]);
578 base::debug::TraceEventHandle handle =
579 TRACE_EVENT_API_ADD_TRACE_EVENT(phase,
580 category_group_enabled,
581 name,
583 num_args,
584 arg_names,
585 arg_types,
586 arg_values,
587 convertable_wrappers,
588 flags);
589 blink::Platform::TraceEventHandle result;
590 memcpy(&result, &handle, sizeof(result));
591 return result;
594 void BlinkPlatformImpl::updateTraceEventDuration(
595 const unsigned char* category_group_enabled,
596 const char* name,
597 TraceEventHandle handle) {
598 base::debug::TraceEventHandle traceEventHandle;
599 memcpy(&traceEventHandle, &handle, sizeof(handle));
600 TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(
601 category_group_enabled, name, traceEventHandle);
604 namespace {
606 WebData loadAudioSpatializationResource(const char* name) {
607 #ifdef IDR_AUDIO_SPATIALIZATION_COMPOSITE
608 if (!strcmp(name, "Composite")) {
609 base::StringPiece resource = GetContentClient()->GetDataResource(
610 IDR_AUDIO_SPATIALIZATION_COMPOSITE, ui::SCALE_FACTOR_NONE);
611 return WebData(resource.data(), resource.size());
613 #endif
615 #ifdef IDR_AUDIO_SPATIALIZATION_T000_P000
616 const size_t kExpectedSpatializationNameLength = 31;
617 if (strlen(name) != kExpectedSpatializationNameLength) {
618 return WebData();
621 // Extract the azimuth and elevation from the resource name.
622 int azimuth = 0;
623 int elevation = 0;
624 int values_parsed =
625 sscanf(name, "IRC_Composite_C_R0195_T%3d_P%3d", &azimuth, &elevation);
626 if (values_parsed != 2) {
627 return WebData();
630 // The resource index values go through the elevations first, then azimuths.
631 const int kAngleSpacing = 15;
633 // 0 <= elevation <= 90 (or 315 <= elevation <= 345)
634 // in increments of 15 degrees.
635 int elevation_index =
636 elevation <= 90 ? elevation / kAngleSpacing :
637 7 + (elevation - 315) / kAngleSpacing;
638 bool is_elevation_index_good = 0 <= elevation_index && elevation_index < 10;
640 // 0 <= azimuth < 360 in increments of 15 degrees.
641 int azimuth_index = azimuth / kAngleSpacing;
642 bool is_azimuth_index_good = 0 <= azimuth_index && azimuth_index < 24;
644 const int kNumberOfElevations = 10;
645 const int kNumberOfAudioResources = 240;
646 int resource_index = kNumberOfElevations * azimuth_index + elevation_index;
647 bool is_resource_index_good = 0 <= resource_index &&
648 resource_index < kNumberOfAudioResources;
650 if (is_azimuth_index_good && is_elevation_index_good &&
651 is_resource_index_good) {
652 const int kFirstAudioResourceIndex = IDR_AUDIO_SPATIALIZATION_T000_P000;
653 base::StringPiece resource = GetContentClient()->GetDataResource(
654 kFirstAudioResourceIndex + resource_index, ui::SCALE_FACTOR_NONE);
655 return WebData(resource.data(), resource.size());
657 #endif // IDR_AUDIO_SPATIALIZATION_T000_P000
659 NOTREACHED();
660 return WebData();
663 struct DataResource {
664 const char* name;
665 int id;
666 ui::ScaleFactor scale_factor;
669 const DataResource kDataResources[] = {
670 { "missingImage", IDR_BROKENIMAGE, ui::SCALE_FACTOR_100P },
671 { "missingImage@2x", IDR_BROKENIMAGE, ui::SCALE_FACTOR_200P },
672 { "mediaplayerPause", IDR_MEDIAPLAYER_PAUSE_BUTTON, ui::SCALE_FACTOR_100P },
673 { "mediaplayerPauseHover",
674 IDR_MEDIAPLAYER_PAUSE_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
675 { "mediaplayerPauseDown",
676 IDR_MEDIAPLAYER_PAUSE_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
677 { "mediaplayerPlay", IDR_MEDIAPLAYER_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
678 { "mediaplayerPlayHover",
679 IDR_MEDIAPLAYER_PLAY_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
680 { "mediaplayerPlayDown",
681 IDR_MEDIAPLAYER_PLAY_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
682 { "mediaplayerPlayDisabled",
683 IDR_MEDIAPLAYER_PLAY_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
684 { "mediaplayerSoundLevel3",
685 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON, ui::SCALE_FACTOR_100P },
686 { "mediaplayerSoundLevel3Hover",
687 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
688 { "mediaplayerSoundLevel3Down",
689 IDR_MEDIAPLAYER_SOUND_LEVEL3_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
690 { "mediaplayerSoundLevel2",
691 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON, ui::SCALE_FACTOR_100P },
692 { "mediaplayerSoundLevel2Hover",
693 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
694 { "mediaplayerSoundLevel2Down",
695 IDR_MEDIAPLAYER_SOUND_LEVEL2_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
696 { "mediaplayerSoundLevel1",
697 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON, ui::SCALE_FACTOR_100P },
698 { "mediaplayerSoundLevel1Hover",
699 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
700 { "mediaplayerSoundLevel1Down",
701 IDR_MEDIAPLAYER_SOUND_LEVEL1_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
702 { "mediaplayerSoundLevel0",
703 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON, ui::SCALE_FACTOR_100P },
704 { "mediaplayerSoundLevel0Hover",
705 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
706 { "mediaplayerSoundLevel0Down",
707 IDR_MEDIAPLAYER_SOUND_LEVEL0_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
708 { "mediaplayerSoundDisabled",
709 IDR_MEDIAPLAYER_SOUND_DISABLED, ui::SCALE_FACTOR_100P },
710 { "mediaplayerSliderThumb",
711 IDR_MEDIAPLAYER_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
712 { "mediaplayerSliderThumbHover",
713 IDR_MEDIAPLAYER_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
714 { "mediaplayerSliderThumbDown",
715 IDR_MEDIAPLAYER_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
716 { "mediaplayerVolumeSliderThumb",
717 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB, ui::SCALE_FACTOR_100P },
718 { "mediaplayerVolumeSliderThumbHover",
719 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_HOVER, ui::SCALE_FACTOR_100P },
720 { "mediaplayerVolumeSliderThumbDown",
721 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DOWN, ui::SCALE_FACTOR_100P },
722 { "mediaplayerVolumeSliderThumbDisabled",
723 IDR_MEDIAPLAYER_VOLUME_SLIDER_THUMB_DISABLED, ui::SCALE_FACTOR_100P },
724 { "mediaplayerClosedCaption",
725 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON, ui::SCALE_FACTOR_100P },
726 { "mediaplayerClosedCaptionHover",
727 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
728 { "mediaplayerClosedCaptionDown",
729 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
730 { "mediaplayerClosedCaptionDisabled",
731 IDR_MEDIAPLAYER_CLOSEDCAPTION_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
732 { "mediaplayerFullscreen",
733 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON, ui::SCALE_FACTOR_100P },
734 { "mediaplayerFullscreenHover",
735 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_HOVER, ui::SCALE_FACTOR_100P },
736 { "mediaplayerFullscreenDown",
737 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DOWN, ui::SCALE_FACTOR_100P },
738 { "mediaplayerFullscreenDisabled",
739 IDR_MEDIAPLAYER_FULLSCREEN_BUTTON_DISABLED, ui::SCALE_FACTOR_100P },
740 { "mediaplayerOverlayPlay",
741 IDR_MEDIAPLAYER_OVERLAY_PLAY_BUTTON, ui::SCALE_FACTOR_100P },
742 #if defined(OS_MACOSX)
743 { "overhangPattern", IDR_OVERHANG_PATTERN, ui::SCALE_FACTOR_100P },
744 { "overhangShadow", IDR_OVERHANG_SHADOW, ui::SCALE_FACTOR_100P },
745 #endif
746 { "panIcon", IDR_PAN_SCROLL_ICON, ui::SCALE_FACTOR_100P },
747 { "searchCancel", IDR_SEARCH_CANCEL, ui::SCALE_FACTOR_100P },
748 { "searchCancelPressed", IDR_SEARCH_CANCEL_PRESSED, ui::SCALE_FACTOR_100P },
749 { "searchMagnifier", IDR_SEARCH_MAGNIFIER, ui::SCALE_FACTOR_100P },
750 { "searchMagnifierResults",
751 IDR_SEARCH_MAGNIFIER_RESULTS, ui::SCALE_FACTOR_100P },
752 { "textAreaResizeCorner", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_100P },
753 { "textAreaResizeCorner@2x", IDR_TEXTAREA_RESIZER, ui::SCALE_FACTOR_200P },
754 { "generatePassword", IDR_PASSWORD_GENERATION_ICON, ui::SCALE_FACTOR_100P },
755 { "generatePasswordHover",
756 IDR_PASSWORD_GENERATION_ICON_HOVER, ui::SCALE_FACTOR_100P },
757 #ifdef IDR_PICKER_COMMON_JS
758 { "pickerCommon.js", IDR_PICKER_COMMON_JS, ui::SCALE_FACTOR_NONE },
759 { "pickerCommon.css", IDR_PICKER_COMMON_CSS, ui::SCALE_FACTOR_NONE },
760 { "calendarPicker.js", IDR_CALENDAR_PICKER_JS, ui::SCALE_FACTOR_NONE },
761 { "calendarPicker.css", IDR_CALENDAR_PICKER_CSS, ui::SCALE_FACTOR_NONE },
762 { "pickerButton.css", IDR_PICKER_BUTTON_CSS, ui::SCALE_FACTOR_NONE },
763 { "suggestionPicker.js", IDR_SUGGESTION_PICKER_JS, ui::SCALE_FACTOR_NONE },
764 { "suggestionPicker.css", IDR_SUGGESTION_PICKER_CSS, ui::SCALE_FACTOR_NONE },
765 { "colorSuggestionPicker.js",
766 IDR_COLOR_SUGGESTION_PICKER_JS, ui::SCALE_FACTOR_NONE },
767 { "colorSuggestionPicker.css",
768 IDR_COLOR_SUGGESTION_PICKER_CSS, ui::SCALE_FACTOR_NONE },
769 #endif
772 } // namespace
774 WebData BlinkPlatformImpl::loadResource(const char* name) {
775 // Some clients will call into this method with an empty |name| when they have
776 // optional resources. For example, the PopupMenuChromium code can have icons
777 // for some Autofill items but not for others.
778 if (!strlen(name))
779 return WebData();
781 // Check the name prefix to see if it's an audio resource.
782 if (StartsWithASCII(name, "IRC_Composite", true) ||
783 StartsWithASCII(name, "Composite", true))
784 return loadAudioSpatializationResource(name);
786 // TODO(flackr): We should use a better than linear search here, a trie would
787 // be ideal.
788 for (size_t i = 0; i < arraysize(kDataResources); ++i) {
789 if (!strcmp(name, kDataResources[i].name)) {
790 base::StringPiece resource = GetContentClient()->GetDataResource(
791 kDataResources[i].id, kDataResources[i].scale_factor);
792 return WebData(resource.data(), resource.size());
796 NOTREACHED() << "Unknown image resource " << name;
797 return WebData();
800 WebString BlinkPlatformImpl::queryLocalizedString(
801 WebLocalizedString::Name name) {
802 int message_id = ToMessageID(name);
803 if (message_id < 0)
804 return WebString();
805 return GetContentClient()->GetLocalizedString(message_id);
808 WebString BlinkPlatformImpl::queryLocalizedString(
809 WebLocalizedString::Name name, int numeric_value) {
810 return queryLocalizedString(name, base::IntToString16(numeric_value));
813 WebString BlinkPlatformImpl::queryLocalizedString(
814 WebLocalizedString::Name name, const WebString& value) {
815 int message_id = ToMessageID(name);
816 if (message_id < 0)
817 return WebString();
818 return ReplaceStringPlaceholders(GetContentClient()->GetLocalizedString(
819 message_id), value, NULL);
822 WebString BlinkPlatformImpl::queryLocalizedString(
823 WebLocalizedString::Name name,
824 const WebString& value1,
825 const WebString& value2) {
826 int message_id = ToMessageID(name);
827 if (message_id < 0)
828 return WebString();
829 std::vector<base::string16> values;
830 values.reserve(2);
831 values.push_back(value1);
832 values.push_back(value2);
833 return ReplaceStringPlaceholders(
834 GetContentClient()->GetLocalizedString(message_id), values, NULL);
837 double BlinkPlatformImpl::currentTime() {
838 return base::Time::Now().ToDoubleT();
841 double BlinkPlatformImpl::monotonicallyIncreasingTime() {
842 return base::TimeTicks::Now().ToInternalValue() /
843 static_cast<double>(base::Time::kMicrosecondsPerSecond);
846 void BlinkPlatformImpl::cryptographicallyRandomValues(
847 unsigned char* buffer, size_t length) {
848 base::RandBytes(buffer, length);
851 void BlinkPlatformImpl::setSharedTimerFiredFunction(void (*func)()) {
852 shared_timer_func_ = func;
855 void BlinkPlatformImpl::setSharedTimerFireInterval(
856 double interval_seconds) {
857 shared_timer_fire_time_ = interval_seconds + monotonicallyIncreasingTime();
858 if (shared_timer_suspended_) {
859 shared_timer_fire_time_was_set_while_suspended_ = true;
860 return;
863 // By converting between double and int64 representation, we run the risk
864 // of losing precision due to rounding errors. Performing computations in
865 // microseconds reduces this risk somewhat. But there still is the potential
866 // of us computing a fire time for the timer that is shorter than what we
867 // need.
868 // As the event loop will check event deadlines prior to actually firing
869 // them, there is a risk of needlessly rescheduling events and of
870 // needlessly looping if sleep times are too short even by small amounts.
871 // This results in measurable performance degradation unless we use ceil() to
872 // always round up the sleep times.
873 int64 interval = static_cast<int64>(
874 ceil(interval_seconds * base::Time::kMillisecondsPerSecond)
875 * base::Time::kMicrosecondsPerMillisecond);
877 if (interval < 0)
878 interval = 0;
880 shared_timer_.Stop();
881 shared_timer_.Start(FROM_HERE, base::TimeDelta::FromMicroseconds(interval),
882 this, &BlinkPlatformImpl::DoTimeout);
883 OnStartSharedTimer(base::TimeDelta::FromMicroseconds(interval));
886 void BlinkPlatformImpl::stopSharedTimer() {
887 shared_timer_.Stop();
890 void BlinkPlatformImpl::callOnMainThread(
891 void (*func)(void*), void* context) {
892 main_loop_->PostTask(FROM_HERE, base::Bind(func, context));
895 blink::WebGestureCurve* BlinkPlatformImpl::createFlingAnimationCurve(
896 blink::WebGestureDevice device_source,
897 const blink::WebFloatPoint& velocity,
898 const blink::WebSize& cumulative_scroll) {
899 #if defined(OS_ANDROID)
900 return FlingAnimatorImpl::CreateAndroidGestureCurve(
901 velocity,
902 cumulative_scroll);
903 #endif
905 if (device_source == blink::WebGestureDeviceTouchscreen)
906 return fling_curve_configuration_->CreateForTouchScreen(velocity,
907 cumulative_scroll);
909 return fling_curve_configuration_->CreateForTouchPad(velocity,
910 cumulative_scroll);
913 void BlinkPlatformImpl::didStartWorkerRunLoop(
914 const blink::WebWorkerRunLoop& runLoop) {
915 WorkerTaskRunner* worker_task_runner = WorkerTaskRunner::Instance();
916 worker_task_runner->OnWorkerRunLoopStarted(runLoop);
919 void BlinkPlatformImpl::didStopWorkerRunLoop(
920 const blink::WebWorkerRunLoop& runLoop) {
921 WorkerTaskRunner* worker_task_runner = WorkerTaskRunner::Instance();
922 worker_task_runner->OnWorkerRunLoopStopped(runLoop);
925 blink::WebCrypto* BlinkPlatformImpl::crypto() {
926 WebCryptoImpl::EnsureInit();
927 return &web_crypto_;
931 WebThemeEngine* BlinkPlatformImpl::themeEngine() {
932 return &native_theme_engine_;
935 WebFallbackThemeEngine* BlinkPlatformImpl::fallbackThemeEngine() {
936 return &fallback_theme_engine_;
939 blink::Platform::FileHandle BlinkPlatformImpl::databaseOpenFile(
940 const blink::WebString& vfs_file_name, int desired_flags) {
941 #if defined(OS_WIN)
942 return INVALID_HANDLE_VALUE;
943 #elif defined(OS_POSIX)
944 return -1;
945 #endif
948 int BlinkPlatformImpl::databaseDeleteFile(
949 const blink::WebString& vfs_file_name, bool sync_dir) {
950 return -1;
953 long BlinkPlatformImpl::databaseGetFileAttributes(
954 const blink::WebString& vfs_file_name) {
955 return 0;
958 long long BlinkPlatformImpl::databaseGetFileSize(
959 const blink::WebString& vfs_file_name) {
960 return 0;
963 long long BlinkPlatformImpl::databaseGetSpaceAvailableForOrigin(
964 const blink::WebString& origin_identifier) {
965 return 0;
968 blink::WebString BlinkPlatformImpl::signedPublicKeyAndChallengeString(
969 unsigned key_size_index,
970 const blink::WebString& challenge,
971 const blink::WebURL& url) {
972 return blink::WebString("");
975 static scoped_ptr<base::ProcessMetrics> CurrentProcessMetrics() {
976 using base::ProcessMetrics;
977 #if defined(OS_MACOSX)
978 return scoped_ptr<ProcessMetrics>(
979 // The default port provider is sufficient to get data for the current
980 // process.
981 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle(),
982 NULL));
983 #else
984 return scoped_ptr<ProcessMetrics>(
985 ProcessMetrics::CreateProcessMetrics(base::GetCurrentProcessHandle()));
986 #endif
989 static size_t getMemoryUsageMB(bool bypass_cache) {
990 size_t current_mem_usage = 0;
991 MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::GetInstance();
992 if (!bypass_cache &&
993 mem_usage_cache_singleton->IsCachedValueValid(&current_mem_usage))
994 return current_mem_usage;
996 current_mem_usage = GetMemoryUsageKB() >> 10;
997 mem_usage_cache_singleton->SetMemoryValue(current_mem_usage);
998 return current_mem_usage;
1001 size_t BlinkPlatformImpl::memoryUsageMB() {
1002 return getMemoryUsageMB(false);
1005 size_t BlinkPlatformImpl::actualMemoryUsageMB() {
1006 return getMemoryUsageMB(true);
1009 size_t BlinkPlatformImpl::physicalMemoryMB() {
1010 return static_cast<size_t>(base::SysInfo::AmountOfPhysicalMemoryMB());
1013 size_t BlinkPlatformImpl::virtualMemoryLimitMB() {
1014 return static_cast<size_t>(base::SysInfo::AmountOfVirtualMemoryMB());
1017 size_t BlinkPlatformImpl::numberOfProcessors() {
1018 return static_cast<size_t>(base::SysInfo::NumberOfProcessors());
1021 void BlinkPlatformImpl::startHeapProfiling(
1022 const blink::WebString& prefix) {
1023 // FIXME(morrita): Make this built on windows.
1024 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1025 HeapProfilerStart(prefix.utf8().data());
1026 #endif
1029 void BlinkPlatformImpl::stopHeapProfiling() {
1030 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1031 HeapProfilerStop();
1032 #endif
1035 void BlinkPlatformImpl::dumpHeapProfiling(
1036 const blink::WebString& reason) {
1037 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1038 HeapProfilerDump(reason.utf8().data());
1039 #endif
1042 WebString BlinkPlatformImpl::getHeapProfile() {
1043 #if !defined(NO_TCMALLOC) && defined(USE_TCMALLOC) && !defined(OS_WIN)
1044 char* data = GetHeapProfile();
1045 WebString result = WebString::fromUTF8(std::string(data));
1046 free(data);
1047 return result;
1048 #else
1049 return WebString();
1050 #endif
1053 bool BlinkPlatformImpl::processMemorySizesInBytes(
1054 size_t* private_bytes,
1055 size_t* shared_bytes) {
1056 return CurrentProcessMetrics()->GetMemoryBytes(private_bytes, shared_bytes);
1059 bool BlinkPlatformImpl::memoryAllocatorWasteInBytes(size_t* size) {
1060 return base::allocator::GetAllocatorWasteSize(size);
1063 blink::WebDiscardableMemory*
1064 BlinkPlatformImpl::allocateAndLockDiscardableMemory(size_t bytes) {
1065 base::DiscardableMemoryType type =
1066 base::DiscardableMemory::GetPreferredType();
1067 if (type == base::DISCARDABLE_MEMORY_TYPE_EMULATED)
1068 return NULL;
1069 return content::WebDiscardableMemoryImpl::CreateLockedMemory(bytes).release();
1072 size_t BlinkPlatformImpl::maxDecodedImageBytes() {
1073 #if defined(OS_ANDROID)
1074 if (base::SysInfo::IsLowEndDevice()) {
1075 // Limit image decoded size to 3M pixels on low end devices.
1076 // 4 is maximum number of bytes per pixel.
1077 return 3 * 1024 * 1024 * 4;
1079 // For other devices, limit decoded image size based on the amount of physical
1080 // memory.
1081 // In some cases all physical memory is not accessible by Chromium, as it can
1082 // be reserved for direct use by certain hardware. Thus, we set the limit so
1083 // that 1.6GB of reported physical memory on a 2GB device is enough to set the
1084 // limit at 16M pixels, which is a desirable value since 4K*4K is a relatively
1085 // common texture size.
1086 return base::SysInfo::AmountOfPhysicalMemory() / 25;
1087 #else
1088 return noDecodedImageByteLimit;
1089 #endif
1092 void BlinkPlatformImpl::SetFlingCurveParameters(
1093 const std::vector<float>& new_touchpad,
1094 const std::vector<float>& new_touchscreen) {
1095 fling_curve_configuration_->SetCurveParameters(new_touchpad, new_touchscreen);
1098 void BlinkPlatformImpl::SuspendSharedTimer() {
1099 ++shared_timer_suspended_;
1102 void BlinkPlatformImpl::ResumeSharedTimer() {
1103 DCHECK_GT(shared_timer_suspended_, 0);
1105 // The shared timer may have fired or been adjusted while we were suspended.
1106 if (--shared_timer_suspended_ == 0 &&
1107 (!shared_timer_.IsRunning() ||
1108 shared_timer_fire_time_was_set_while_suspended_)) {
1109 shared_timer_fire_time_was_set_while_suspended_ = false;
1110 setSharedTimerFireInterval(
1111 shared_timer_fire_time_ - monotonicallyIncreasingTime());
1115 // static
1116 void BlinkPlatformImpl::DestroyCurrentThread(void* thread) {
1117 WebThreadImplForMessageLoop* impl =
1118 static_cast<WebThreadImplForMessageLoop*>(thread);
1119 delete impl;
1122 } // namespace content