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