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