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