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