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